"""
Local JSON cache for subject metadata.

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

import os
import json
from typing import Dict, Optional

from ktunotes.scraper import scrape_all

CACHE_DIR = os.path.join(os.path.expanduser('~'), '.ktunotes_cache')
CACHE_FILE = os.path.join(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 os.path.exists(CACHE_FILE):
        return {}
    try:
        with open(CACHE_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return {}


def save_cache(data: Dict[str, dict]) -> None:
    """Save subject data to the cache file."""
    os.makedirs(CACHE_DIR, exist_ok=True)
    with open(CACHE_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


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())
