"""AuditRecorder — append-only audit trail, saved as JSON to .fliiq/audit/.

DEPRECATED: Superseded by runtime/agent/audit.py which extracts audit from message history.
Kept for reference only. Will be removed in a follow-up PR.
"""

import json
from datetime import datetime, timezone
from pathlib import Path

import structlog

from fliiq.runtime.planning.models import AuditEntry, AuditTrail, Plan

log = structlog.get_logger()


class AuditRecorder:
    def __init__(self, prompt: str, audit_dir: Path | None = None):
        self._trail = AuditTrail(prompt=prompt)
        self._audit_dir = audit_dir or Path(".fliiq/audit")
        self._record_event("session_started")

    def record_plan(self, plan: Plan) -> None:
        self._trail.plan = plan
        self._record_event("plan_generated", {"goal": plan.goal, "step_count": len(plan.steps)})

    def record_event(self, event: str, data: dict | None = None) -> None:
        self._record_event(event, data)

    def _record_event(self, event: str, data: dict | None = None) -> None:
        self._trail.entries.append(AuditEntry(event=event, data=data))

    def save(self) -> Path:
        """Write audit trail to .fliiq/audit/{timestamp}_{id}.json. Returns path."""
        self._trail.completed_at = datetime.now(timezone.utc)
        self._record_event("session_completed")

        self._audit_dir.mkdir(parents=True, exist_ok=True)
        ts = self._trail.started_at.strftime("%Y%m%d_%H%M%S")
        filename = f"{ts}_{self._trail.id}.json"
        path = self._audit_dir / filename

        path.write_text(self._trail.model_dump_json(indent=2))
        log.info("audit_saved", path=str(path))
        return path
