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

from __future__ import annotations

import json
from pathlib import Path

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

CONFIG_DIR = Path.home() / ".reddit-mcp"
COOKIES_PATH = CONFIG_DIR / "cookies.json"
LAUNCHER_PATH = CONFIG_DIR / "launcher.py"
META_PATH = CONFIG_DIR / "meta.json"
BROWSER_PROFILE = 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 ~/.reddit-mcp/ if it doesn't exist, with 700 permissions."""
    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.)."""
    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")
