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.duckdb

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


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.duckdb"
    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.duckdb
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.duckdb"
