import os
import pytest
from pathlib import Path
from transduck.config import load_config, TransduckConfig


@pytest.fixture
def config_yaml(tmp_path):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test-project
  context: "A test travel site"

languages:
  source: EN
  targets:
    - DE
    - ES

storage:
  path: ./translations.db

backend:
  api_key_env: OPENAI_API_KEY
  model: gpt-4.1-mini
  timeout_seconds: 10
  max_retries: 2
""")
    return config


def test_load_config_shared_url_default_none(config_yaml):
    cfg = load_config(config_yaml)
    assert cfg.shared_url is None


def test_load_config_shared_url_from_yaml(tmp_path):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
  shared_url: postgres://localhost/transduck
backend:
  api_key_env: OPENAI_API_KEY
  model: gpt-4.1-mini
""")
    cfg = load_config(config)
    assert cfg.shared_url == "postgres://localhost/transduck"


def test_load_config_shared_url_env_overrides_yaml(tmp_path, monkeypatch):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
  shared_url: postgres://localhost/from-yaml
backend:
  api_key_env: OPENAI_API_KEY
  model: gpt-4.1-mini
""")
    monkeypatch.setenv("TRANSDUCK_SHARED_URL", "postgres://localhost/from-env")
    cfg = load_config(config)
    assert cfg.shared_url == "postgres://localhost/from-env"


def test_load_config_shared_url_from_env_only(config_yaml, monkeypatch):
    monkeypatch.setenv("TRANSDUCK_SHARED_URL", "postgres://localhost/env-only")
    cfg = load_config(config_yaml)
    assert cfg.shared_url == "postgres://localhost/env-only"


def test_load_config_from_path(config_yaml):
    cfg = load_config(config_yaml)
    assert cfg.project_name == "test-project"
    assert cfg.project_context == "A test travel site"
    assert cfg.source_lang == "EN"
    assert cfg.target_langs == ["DE", "ES"]
    assert cfg.storage_path.name == "translations.db"
    assert cfg.backend_model == "gpt-4.1-mini"
    assert cfg.backend_timeout == 10
    assert cfg.backend_max_retries == 2
    assert cfg.api_key_env == "OPENAI_API_KEY"


def test_load_config_normalizes_language_codes(tmp_path):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: en
  targets: [de, es]
storage:
  path: ./translations.db
backend:
  api_key_env: OPENAI_API_KEY
  model: gpt-4.1-mini
  timeout_seconds: 10
  max_retries: 2
""")
    cfg = load_config(config)
    assert cfg.source_lang == "EN"
    assert cfg.target_langs == ["DE", "ES"]


def test_load_config_discovery_from_env(config_yaml, monkeypatch):
    monkeypatch.setenv("TRANSDUCK_CONFIG", str(config_yaml))
    cfg = load_config()
    assert cfg.project_name == "test-project"


def test_load_config_discovery_from_cwd(config_yaml, monkeypatch):
    monkeypatch.chdir(config_yaml.parent)
    cfg = load_config()
    assert cfg.project_name == "test-project"


def test_load_config_discovery_walks_up(config_yaml, monkeypatch):
    subdir = config_yaml.parent / "sub" / "deep"
    subdir.mkdir(parents=True)
    monkeypatch.chdir(subdir)
    cfg = load_config()
    assert cfg.project_name == "test-project"


def test_load_config_raises_if_not_found(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    monkeypatch.delenv("TRANSDUCK_CONFIG", raising=False)
    with pytest.raises(FileNotFoundError):
        load_config()


def test_storage_path_relative_to_config(config_yaml):
    cfg = load_config(config_yaml)
    assert cfg.storage_path == config_yaml.parent / "translations.db"


def test_load_config_with_provider(tmp_path):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
backend:
  provider: claude_api
  api_key_env: ANTHROPIC_API_KEY
  model: claude-haiku-4-5-20251001
  timeout_seconds: 15
  max_retries: 3
""")
    cfg = load_config(config)
    assert cfg.provider == "claude_api"
    assert cfg.api_key_env == "ANTHROPIC_API_KEY"
    assert cfg.backend_model == "claude-haiku-4-5-20251001"


def test_load_config_defaults_to_openai(config_yaml):
    cfg = load_config(config_yaml)
    assert cfg.provider == "openai"


def test_load_config_claude_code_forces_read_only(tmp_path):
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
backend:
  provider: claude_code
  token_env: CLAUDE_CODE_OAUTH_TOKEN
""")
    cfg = load_config(config)
    assert cfg.provider == "claude_code"
    assert cfg.token_env == "CLAUDE_CODE_OAUTH_TOKEN"
    assert cfg.read_only is True


def test_load_config_claude_code_minimal(tmp_path):
    """claude_code config can omit model, api_key_env, timeout, max_retries."""
    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
backend:
  provider: claude_code
""")
    cfg = load_config(config)
    assert cfg.provider == "claude_code"
    assert cfg.read_only is True
    assert cfg.backend_model == "gpt-4.1-mini"  # default, unused


def test_load_config_loads_dotenv(tmp_path, monkeypatch):
    """load_config picks up variables from a .env file."""
    env_file = tmp_path / ".env"
    env_file.write_text("TRANSDUCK_TEST_KEY=from-dotenv\n")
    monkeypatch.chdir(tmp_path)
    monkeypatch.delenv("TRANSDUCK_TEST_KEY", raising=False)

    config = tmp_path / "transduck.yaml"
    config.write_text("""
project:
  name: dotenv-test
  context: "test"
languages:
  source: EN
  targets: [DE]
storage:
  path: ./translations.db
backend:
  api_key_env: TRANSDUCK_TEST_KEY
  model: gpt-4.1-mini
""")
    cfg = load_config(config)
    assert os.environ.get("TRANSDUCK_TEST_KEY") == "from-dotenv"
    assert cfg.api_key_env == "TRANSDUCK_TEST_KEY"
