import json
import time
from pathlib import Path

import pandas as pd

from config import CACHE_DIR


def _cache_path(key: str) -> Path:
    safe = key.replace("/", "_").replace(" ", "_")
    return CACHE_DIR / f"{safe}.pkl"


def _meta_path(key: str) -> Path:
    safe = key.replace("/", "_").replace(" ", "_")
    return CACHE_DIR / f"{safe}.meta"


def get_cached(key: str, max_age_hours: float = 4):
    p = _cache_path(key)
    m = _meta_path(key)
    if not p.exists() or not m.exists():
        return None
    meta = json.loads(m.read_text())
    age_hours = (time.time() - meta["ts"]) / 3600
    if age_hours > max_age_hours:
        return None
    return pd.read_pickle(p)


def set_cached(key: str, df: pd.DataFrame):
    df.to_pickle(_cache_path(key))
    meta = {"ts": time.time(), "rows": len(df)}
    _meta_path(key).write_text(json.dumps(meta))


def clear_cache():
    for f in CACHE_DIR.glob("*.pkl"):
        f.unlink()
    for f in CACHE_DIR.glob("*.meta"):
        f.unlink()
