"""Tests for environment-based configuration."""

from __future__ import annotations

import os
from pathlib import Path
from unittest.mock import patch

import pytest
from helpers import FAKE_RSA_PEM

from github_app.config import Config, default_plugin_dir, load_private_key


def test_load_private_key_from_env():
    with patch.dict(os.environ, {"GITHUB_PRIVATE_KEY": "PEM-DATA"}):
        assert load_private_key() == "PEM-DATA"


def test_load_private_key_from_file(tmp_path):
    key_file = tmp_path / "key.pem"
    key_file.write_text("FILE-PEM")
    env = {"GITHUB_PRIVATE_KEY_PATH": str(key_file)}
    with patch.dict(os.environ, env, clear=False):
        # Remove the raw key so the file path branch is taken.
        os.environ.pop("GITHUB_PRIVATE_KEY", None)
        result = load_private_key()
    assert result == "FILE-PEM"


def test_load_private_key_missing():
    with (
        patch.dict(
            os.environ,
            {},
            clear=True,
        ),
        pytest.raises(ValueError, match="GITHUB_PRIVATE_KEY"),
    ):
        load_private_key()


def test_default_plugin_dir_from_env(tmp_path):
    with patch.dict(os.environ, {"PLUGIN_DIR": str(tmp_path)}):
        assert default_plugin_dir() == tmp_path


def test_default_plugin_dir_fallback():
    with patch.dict(os.environ, {}, clear=False):
        os.environ.pop("PLUGIN_DIR", None)
        result = default_plugin_dir()
    # Should be relative to config.py's location (assembled dist/).
    assert result.name == "dist"


def test_config_construction():
    """Config can be constructed when all env vars are set."""
    env = {
        "GITHUB_APP_ID": "42",
        "GITHUB_PRIVATE_KEY": FAKE_RSA_PEM,
        "GITHUB_WEBHOOK_SECRET": "secret",
    }
    with patch.dict(os.environ, env):
        cfg = Config()
    assert cfg.app_id == 42
    assert isinstance(cfg.app_id, int)
    assert cfg.private_key == FAKE_RSA_PEM
    assert cfg.webhook_secret == "secret"
    assert cfg.claude_model == "us.anthropic.claude-sonnet-4-5-20250929-v1:0"
    assert cfg.port == 8000


def test_config_app_id_non_numeric():
    """Non-numeric GITHUB_APP_ID raises ValueError."""
    env = {
        "GITHUB_APP_ID": "not-a-number",
        "GITHUB_PRIVATE_KEY": FAKE_RSA_PEM,
        "GITHUB_WEBHOOK_SECRET": "secret",
    }
    with patch.dict(os.environ, env), pytest.raises(ValueError):
        Config()


def test_config_workspace_dir_default():
    env = {
        "GITHUB_APP_ID": "1",
        "GITHUB_PRIVATE_KEY": FAKE_RSA_PEM,
        "GITHUB_WEBHOOK_SECRET": "secret",
    }
    with patch.dict(os.environ, env):
        cfg = Config()
    assert cfg.workspace_dir == Path("/tmp/codeflash-workspaces")
