"""
Local JSON cache for subject metadata.

Stores subject data at ~/.ktunotes_cache/subjects.json
"""

import json
from pathlib import Path
from typing import Dict, Optional

from ktunotes.scraper import scrape_all

CACHE_DIR = Path.home() / ".ktunotes_cache"
CACHE_FILE = CACHE_DIR / "subjects.json"


def load_cache() -> Dict[str, dict]:
    """
    Load subjects from the cache file.
    Returns empty dict if cache doesn't exist or is corrupt.
    """
    if not CACHE_FILE.exists():
        return {}
    try:
        return json.loads(CACHE_FILE.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, IOError):
        return {}


def save_cache(data: Dict[str, dict]) -> None:
    """Save subject data to the cache file."""
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    CACHE_FILE.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )


def update_cache() -> Dict[str, dict]:
    """
    Scrape ktunotes.live and regenerate the cache.
    Returns the new subject data.
    """
    data = scrape_all()
    save_cache(data)
    return data


def get_subject(code: str) -> Optional[dict]:
    """
    Look up a subject by its code (case-insensitive).
    Returns the subject dict or None if not found.
    """
    cache = load_cache()
    return cache.get(code.lower())
