from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict, List

from bastion.models import AIBOM, CapabilitySurface, DriftEvent, SecurityState


def write_security_state(state: SecurityState, bastion_dir: Path) -> None:
    path = bastion_dir / "security_state.json"
    with open(path, "w") as f:
        json.dump(state.to_dict(), f, indent=2)


def write_capability_surface(surface: CapabilitySurface, bastion_dir: Path) -> None:
    path = bastion_dir / "capability_surface.json"
    with open(path, "w") as f:
        json.dump(surface.to_dict(), f, indent=2)


def write_drift_summary(drift_events: List[DriftEvent], bastion_dir: Path) -> None:
    path = bastion_dir / "drift_summary.json"
    data = {
        "drift_events": [e.to_dict() for e in drift_events],
        "total_events": len(drift_events),
    }
    with open(path, "w") as f:
        json.dump(data, f, indent=2)


def write_aibom(aibom: AIBOM, bastion_dir: Path) -> None:
    path = bastion_dir / "aibom.json"
    with open(path, "w") as f:
        json.dump(aibom.to_dict(), f, indent=2)


def append_event(event_dict: Dict[str, Any], bastion_dir: Path) -> None:
    path = bastion_dir / "events.log.jsonl"
    with open(path, "a") as f:
        f.write(json.dumps(event_dict) + "\n")
