
from __future__ import annotations

import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any

BASE_DIR = Path(__file__).resolve().parents[1]
DATA_DIR = BASE_DIR / "data"
CACHE_DIR = DATA_DIR / "cache"
CACHE_DIR.mkdir(parents=True, exist_ok=True)


def utc_now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def cache_path(name: str) -> Path:
    safe = name.replace("/", "_").replace("..", "_")
    return CACHE_DIR / safe


def read_json_cache(name: str) -> dict[str, Any] | list[Any] | None:
    path = cache_path(name)
    if not path.exists():
        return None
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def write_json_cache(name: str, data: Any) -> Path:
    path = cache_path(name)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    return path


def is_fresh(name: str, max_age_days: int) -> bool:
    path = cache_path(name)
    if not path.exists():
        return False
    modified = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
    return datetime.now(timezone.utc) - modified <= timedelta(days=max_age_days)


def describe_cache(name: str) -> dict[str, Any]:
    path = cache_path(name)
    if not path.exists():
        return {"exists": False, "path": str(path.relative_to(BASE_DIR))}
    modified = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
    return {
        "exists": True,
        "path": str(path.relative_to(BASE_DIR)),
        "updated_at": modified.isoformat(),
        "size_bytes": path.stat().st_size,
    }
