from __future__ import annotations

import argparse

from nbdraw.config import build_configs, parse_kv_list, resolve_config_path


def make_args(**overrides):
    defaults = {
        "config": None,
        "base_url": None,
        "api_key": None,
        "timeout": None,
        "connect_timeout": None,
        "retries": None,
        "backoff_base": None,
        "backoff_cap": None,
        "model": None,
        "aspect_ratio": None,
        "image_size": None,
        "web_hook": None,
        "set": None,
        "poll_interval": None,
        "max_wait": None,
        "heartbeat": None,
        "prompt": None,
        "prompt_file": None,
        "stdin": False,
    }
    defaults.update(overrides)
    return argparse.Namespace(**defaults)


def test_parse_kv_list_types():
    result = parse_kv_list(["seed=123", "flag=true", "ratio=1.5", "name=abc"])
    assert result["seed"] == 123
    assert result["flag"] is True
    assert result["ratio"] == 1.5
    assert result["name"] == "abc"


def test_resolve_config_path_prefers_new_file(tmp_path):
    (tmp_path / "nbdraw.toml").write_text("[client]\napi_key='a'\n", encoding="utf-8")
    (tmp_path / "grsai_draw.toml").write_text("[client]\napi_key='b'\n", encoding="utf-8")

    path = resolve_config_path(None, cwd=tmp_path)
    assert path and path.endswith("nbdraw.toml")


def test_resolve_config_path_fallback_legacy(tmp_path):
    (tmp_path / "grsai_draw.toml").write_text("[client]\napi_key='b'\n", encoding="utf-8")

    path = resolve_config_path(None, cwd=tmp_path)
    assert path and path.endswith("grsai_draw.toml")


def test_build_configs_precedence(monkeypatch, tmp_path):
    config = tmp_path / "nbdraw.toml"
    config.write_text(
        "\n".join(
            [
                "[client]",
                "api_key = 'file-key'",
                "base_url = 'https://file.example.com'",
                "",
                "[draw]",
                "model = 'nano-banana-pro'",
            ]
        ),
        encoding="utf-8",
    )

    monkeypatch.setenv("GRSAI_API_KEY", "env-key")
    monkeypatch.setenv("GRSAI_BASE_URL", "https://env.example.com")

    args = make_args(config=str(config), api_key="cli-key")
    client_cfg, draw_cfg, _ = build_configs(args)

    assert client_cfg.api_key == "cli-key"
    assert client_cfg.base_url == "https://env.example.com"
    assert draw_cfg.model == "nano-banana-pro"
