from __future__ import annotations

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

from core.database import EventDatabase


class AuditLogger:
    """Append-only audit trail for remediation actions and system changes."""

    def __init__(self, db_path: Optional[str | Path] = None):
        self.db = EventDatabase(db_path)

    def record(
        self,
        action: str,
        actor: str,
        target: str,
        details: Dict[str, Any] | str,
        finding: Optional[str] = None,
        transaction_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        payload = details if isinstance(details, dict) else {"message": details}
        if finding is not None:
            payload["finding"] = finding
        if transaction_id is not None:
            payload["transaction_id"] = transaction_id

        entry = {
            "timestamp": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).isoformat(timespec="milliseconds"),
            "action": action,
            "actor": actor,
            "object": target,
            "details": json.dumps(payload, sort_keys=True),
        }
        self.db.insert_audit_event(entry["action"], entry["actor"], entry["object"], entry["details"])
        return entry

    def list_entries(self, limit: int = 100) -> List[Dict[str, Any]]:
        conn = self.db._connect()
        try:
            rows = conn.execute(
                "SELECT timestamp, action, actor, object, details FROM audit_log ORDER BY audit_id DESC LIMIT ?",
                (limit,),
            ).fetchall()
            return [dict(row) for row in rows]
        finally:
            conn.close()

    def close(self) -> None:
        self.db.close()
