"""Path constants and configuration for reddit-mcp."""

from __future__ import annotations

import json
import shutil
from pathlib import Path

# --- Directory & file paths ---------------------------------------------------

SHARED_HOME_DIR = Path.home() / ".mkterswingman"
LEGACY_CONFIG_DIR = Path.home() / ".reddit-mcp"
CONFIG_DIR = SHARED_HOME_DIR / "reddit-mcp"
COOKIES_PATH = CONFIG_DIR / "cookies.json"
META_PATH = CONFIG_DIR / "meta.json"
BROWSER_PROFILE = CONFIG_DIR / "browser-profile"
LEGACY_COOKIES_PATH = LEGACY_CONFIG_DIR / "cookies.json"
LEGACY_META_PATH = LEGACY_CONFIG_DIR / "meta.json"
LEGACY_BROWSER_PROFILE = LEGACY_CONFIG_DIR / "browser-profile"

# --- HTTP client defaults ------------------------------------------------------

# Reddit rate limit: 100 requests per 10-minute window
RATE_LIMIT_FLOOR = 20  # start throttling when remaining < this
RATE_LIMIT_MAX_SLEEP = 10.0  # seconds, cap per-request sleep

# Cookie age warning threshold (days)
# reddit_session JWT has ~181 day TTL; warn 30 days before expiry
COOKIE_AGE_WARN_DAYS = 150

# --- Env var names -------------------------------------------------------------

ENV_TOKEN = "REDDIT_MCP_TOKEN"


def ensure_config_dir() -> None:
    """Create ~/.mkterswingman/reddit-mcp/ if it doesn't exist, migrating legacy ~/.reddit-mcp/."""
    SHARED_HOME_DIR.mkdir(parents=True, exist_ok=True)
    if not CONFIG_DIR.exists() and LEGACY_CONFIG_DIR.exists():
        try:
            shutil.move(str(LEGACY_CONFIG_DIR), str(CONFIG_DIR))
        except OSError:
            CONFIG_DIR.mkdir(parents=True, exist_ok=True)
            _merge_legacy_config_tree()
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    # Best-effort tighten permissions (no-op on Windows)
    try:
        CONFIG_DIR.chmod(0o700)
    except OSError:
        pass


def load_meta() -> dict:
    """Load meta.json (cookie creation time, etc.)."""
    meta_path = META_PATH if META_PATH.exists() else LEGACY_META_PATH
    if not meta_path.exists():
        return {}
    try:
        return json.loads(meta_path.read_text("utf-8"))
    except (json.JSONDecodeError, OSError):
        return {}


def save_meta(data: dict) -> None:
    """Persist meta.json."""
    ensure_config_dir()
    META_PATH.write_text(json.dumps(data, indent=2), "utf-8")


def _merge_legacy_config_tree() -> None:
    for legacy_path, target_path in (
        (LEGACY_COOKIES_PATH, COOKIES_PATH),
        (LEGACY_META_PATH, META_PATH),
    ):
        if legacy_path.exists() and not target_path.exists():
            shutil.copy2(legacy_path, target_path)
    if LEGACY_BROWSER_PROFILE.exists() and not BROWSER_PROFILE.exists():
        shutil.copytree(LEGACY_BROWSER_PROFILE, BROWSER_PROFILE, dirs_exist_ok=True)
