from __future__ import annotations

import json
from pathlib import Path

from reddit_mcp import config as config_module


def test_ensure_config_dir_migrates_legacy_home(monkeypatch, tmp_path: Path) -> None:
    shared_home = tmp_path / ".mkterswingman"
    new_config_dir = shared_home / "reddit-mcp"
    legacy_config_dir = tmp_path / ".reddit-mcp"
    legacy_config_dir.mkdir(parents=True, exist_ok=True)
    (legacy_config_dir / "cookies.json").write_text('{"reddit_session":"ok"}', encoding="utf-8")
    (legacy_config_dir / "meta.json").write_text('{"cookies_created_at":123}', encoding="utf-8")

    monkeypatch.setattr(config_module, "SHARED_HOME_DIR", shared_home)
    monkeypatch.setattr(config_module, "CONFIG_DIR", new_config_dir)
    monkeypatch.setattr(config_module, "COOKIES_PATH", new_config_dir / "cookies.json")
    monkeypatch.setattr(config_module, "META_PATH", new_config_dir / "meta.json")
    monkeypatch.setattr(config_module, "BROWSER_PROFILE", new_config_dir / "browser-profile")
    monkeypatch.setattr(config_module, "LEGACY_CONFIG_DIR", legacy_config_dir)
    monkeypatch.setattr(config_module, "LEGACY_COOKIES_PATH", legacy_config_dir / "cookies.json")
    monkeypatch.setattr(config_module, "LEGACY_META_PATH", legacy_config_dir / "meta.json")
    monkeypatch.setattr(config_module, "LEGACY_BROWSER_PROFILE", legacy_config_dir / "browser-profile")

    config_module.ensure_config_dir()

    assert new_config_dir.exists()
    assert not legacy_config_dir.exists()
    assert json.loads((new_config_dir / "cookies.json").read_text("utf-8"))["reddit_session"] == "ok"
    assert json.loads((new_config_dir / "meta.json").read_text("utf-8"))["cookies_created_at"] == 123


def test_load_meta_falls_back_to_legacy_path(monkeypatch, tmp_path: Path) -> None:
    new_meta = tmp_path / ".mkterswingman" / "reddit-mcp" / "meta.json"
    legacy_meta = tmp_path / ".reddit-mcp" / "meta.json"
    legacy_meta.parent.mkdir(parents=True, exist_ok=True)
    legacy_meta.write_text('{"cookies_created_at":456}', encoding="utf-8")

    monkeypatch.setattr(config_module, "META_PATH", new_meta)
    monkeypatch.setattr(config_module, "LEGACY_META_PATH", legacy_meta)

    assert config_module.load_meta()["cookies_created_at"] == 456
