"""Tests for fliiq init and fliiq doctor commands."""

from pathlib import Path
from unittest.mock import patch

from typer.testing import CliRunner

from fliiq.cli.main import app

runner = CliRunner()


def test_init_global_creates_dirs(tmp_path, monkeypatch):
    fake_global = tmp_path / ".fliiq"
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fake_global)

    # Patch bundled_env_template to return a fake template
    fake_template = tmp_path / "env.template"
    fake_template.write_text("ANTHROPIC_API_KEY=\n")

    with patch("fliiq.runtime.package_data.bundled_env_template", return_value=fake_template):
        result = runner.invoke(app, ["init"])

    assert result.exit_code == 0
    assert fake_global.is_dir()
    assert (fake_global / "audit").is_dir()
    assert (fake_global / "skills").is_dir()
    assert (fake_global / "memory").is_dir()
    assert (fake_global / ".env").is_file()
    assert "ANTHROPIC_API_KEY" in (fake_global / ".env").read_text()


def test_init_project_creates_dirs(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    result = runner.invoke(app, ["init", "--project"])

    assert result.exit_code == 0
    fliiq_dir = tmp_path / ".fliiq"
    assert fliiq_dir.is_dir()
    assert (fliiq_dir / "audit").is_dir()
    assert (fliiq_dir / "jobs").is_dir()
    assert (fliiq_dir / "skills").is_dir()
    assert (fliiq_dir / "memory").is_dir()


def test_init_global_idempotent(tmp_path, monkeypatch):
    fake_global = tmp_path / ".fliiq"
    fake_global.mkdir()
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fake_global)

    fake_template = tmp_path / "env.template"
    fake_template.write_text("KEY=\n")

    with patch("fliiq.runtime.package_data.bundled_env_template", return_value=fake_template):
        result = runner.invoke(app, ["init"])

    assert result.exit_code == 0
    assert "already exists" in result.output


def test_init_project_idempotent(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    (tmp_path / ".fliiq").mkdir()
    result = runner.invoke(app, ["init", "--project"])
    assert result.exit_code == 0
    assert "already exists" in result.output


def test_doctor_all_pass(tmp_path, monkeypatch):
    fake_global = tmp_path / ".fliiq"
    fake_global.mkdir()
    (fake_global / ".env").write_text("ANTHROPIC_API_KEY=sk-test\n")

    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fake_global)
    monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")

    result = runner.invoke(app, ["doctor"])
    assert result.exit_code == 0
    assert "All checks passed" in result.output


def test_doctor_missing_global(tmp_path, monkeypatch):
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", tmp_path / "nonexistent")
    monkeypatch.chdir(tmp_path)

    result = runner.invoke(app, ["doctor"])
    assert result.exit_code == 0
    assert "MISSING" in result.output
    assert "fliiq init" in result.output
