import os
import shutil

import pytest

from debgpt.defaults import Config, migrate_legacy_home


def test_config_initialization(tmp_path, monkeypatch):
    monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / ".config"))
    monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / ".cache"))
    monkeypatch.setenv("OPENAI_API_KEY", "test-key-openai")
    monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key-anthropic")
    monkeypatch.setenv("GOOGLE_API_KEY", "test-key-google")

    config_dir = tmp_path / ".config" / "debgpt"
    config_dir.mkdir(parents=True, exist_ok=True)

    config_file = config_dir / "config.toml"
    config_file.write_text('frontend = "test_frontend"\n[custom]\nkey = "value"\n')

    c = Config(config=str(config_file), verbose=True)

    assert c.openai_api_key == "test-key-openai"
    assert c.anthropic_api_key == "test-key-anthropic"
    assert c.google_api_key == "test-key-google"

    assert c.frontend == "test_frontend"
    assert c["frontend"] == "test_frontend"

    assert getattr(c, "frontend") == "test_frontend"


def test_migrate_legacy_home(tmp_path, monkeypatch):
    legacy_dir = tmp_path / ".debgpt"
    config_dir = tmp_path / ".config" / "debgpt"
    cache_dir = tmp_path / ".cache" / "debgpt"

    monkeypatch.setattr("debgpt.defaults.LEGACY_HOME", str(legacy_dir))
    monkeypatch.setattr("debgpt.defaults.CONFIG_HOME", str(config_dir))
    monkeypatch.setattr("debgpt.defaults.CACHE_HOME", str(cache_dir))
    monkeypatch.setattr("debgpt.defaults.CONFIG", str(config_dir / "config.toml"))
    monkeypatch.setattr("debgpt.defaults.CACHE", str(cache_dir / "cache.sqlite"))

    # 1. Test when legacy dir doesn't exist
    migrate_legacy_home()
    assert not config_dir.exists()

    # 2. Test empty legacy dir
    legacy_dir.mkdir()
    migrate_legacy_home()
    assert not legacy_dir.exists()

    # 3. Test migration of files
    legacy_dir.mkdir()
    (legacy_dir / "config.toml").write_text("config")
    (legacy_dir / "cache.sqlite").write_text("cache")
    (legacy_dir / "log.json").write_text("log")

    migrate_legacy_home()

    assert not legacy_dir.exists()
    assert (config_dir / "config.toml").exists()
    assert (cache_dir / "cache.sqlite").exists()
    assert (cache_dir / "log.json").exists()

    # 4. Test leftovers
    legacy_dir.mkdir()
    (legacy_dir / "config.toml").write_text("config")
    (legacy_dir / "unexpected.txt").write_text("what")

    migrate_legacy_home()
    assert legacy_dir.exists()
    assert (legacy_dir / "unexpected.txt").exists()

    # cleanup
    shutil.rmtree(legacy_dir)
