from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Protocol
import os, json
from .event import AuditEvent, _stable_json

class AuditStore(Protocol):
    def append(self, event: AuditEvent) -> None: ...
    def last_hash(self, correlation_id: str) -> Optional[str]: ...

@dataclass
class JsonlAuditStore:
    path: str = "sentinel_audit.jsonl"
    hash_chain: bool = True

    def _ensure_dir(self) -> None:
        d = os.path.dirname(self.path)
        if d and not os.path.exists(d):
            os.makedirs(d, exist_ok=True)

    def append(self, event: AuditEvent) -> None:
        self._ensure_dir()
        with open(self.path, "a", encoding="utf-8") as f:
            f.write(_stable_json(event.to_dict()))
            f.write("\n")

    def last_hash(self, correlation_id: str) -> Optional[str]:
        if not os.path.exists(self.path):
            return None
        last = None
        with open(self.path, "r", encoding="utf-8") as f:
            for line in f:
                try:
                    obj = json.loads(line)
                except Exception:
                    continue
                if obj.get("correlation_id") == correlation_id:
                    last = obj.get("hash") or last
        return last
