from __future__ import annotations

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


def default_data_dir() -> Path:
    return Path(os.path.expanduser("~")) / ".auditwalk"


def runs_dir(base: Optional[Path] = None) -> Path:
    return (base or default_data_dir()) / "runs"


def ensure_dirs(base: Optional[Path] = None) -> None:
    runs_dir(base).mkdir(parents=True, exist_ok=True)


def write_run_json(run_id: str, payload: Dict[str, Any], base: Optional[Path] = None) -> Path:
    ensure_dirs(base)
    path = runs_dir(base) / f"{run_id}.json"
    path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
    return path


def latest_run_path(base: Optional[Path] = None) -> Optional[Path]:
    directory = runs_dir(base)
    if not directory.exists():
        return None
    items = sorted(directory.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
    return items[0] if items else None


def read_json(path: Path) -> Dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))
