from __future__ import annotations

import os
from pathlib import Path

from typer.testing import CliRunner

from worai import cli as root_cli
from worai.commands import graph as graph_cmd


def test_root_cli_loads_worai_config_from_dotenv(monkeypatch) -> None:
    seen = {}

    def _stub_run(options):
        seen["options"] = options

    monkeypatch.setattr(graph_cmd, "run_graph_sync", _stub_run)

    runner = CliRunner()
    with runner.isolated_filesystem():
        cfg = Path("from-dotenv.toml")
        cfg.write_text("[profile.zrh]\napi_key='wl'\n", encoding="utf-8")
        expected_cfg = cfg.resolve()
        Path(".env").write_text(f"WORAI_CONFIG={expected_cfg}\n", encoding="utf-8")

        result = runner.invoke(root_cli.app, ["--profile", "zrh", "graph", "sync", "run"], env={})
        os.environ.pop("WORAI_CONFIG", None)

    assert result.exit_code == 0
    assert seen["options"].config_path == expected_cfg


def test_root_cli_dotenv_does_not_override_real_env(monkeypatch) -> None:
    seen = {}

    def _stub_run(options):
        seen["options"] = options

    monkeypatch.setattr(graph_cmd, "run_graph_sync", _stub_run)

    runner = CliRunner()
    with runner.isolated_filesystem():
        dotenv_cfg = Path("from-dotenv.toml")
        dotenv_cfg.write_text("[profile.zrh]\napi_key='wl'\n", encoding="utf-8")
        env_cfg = Path("from-env.toml")
        env_cfg.write_text("[profile.zrh]\napi_key='wl'\n", encoding="utf-8")
        expected_env_cfg = env_cfg.resolve()
        Path(".env").write_text(f"WORAI_CONFIG={dotenv_cfg.resolve()}\n", encoding="utf-8")

        result = runner.invoke(
                root_cli.app,
                ["--profile", "zrh", "graph", "sync", "run"],
                env={"WORAI_CONFIG": str(expected_env_cfg)},
            )
        os.environ.pop("WORAI_CONFIG", None)

    assert result.exit_code == 0
    assert seen["options"].config_path == expected_env_cfg
