"""HistoryReader for reading historical audit data from disk."""

import json
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional

logger = logging.getLogger(__name__)


@dataclass
class AuditSummary:
    """Summary of a historical audit."""

    dir_name: str
    timestamp: str
    lens: str
    continuation_id: str
    project_name: Optional[str]
    total_findings: int
    by_severity: dict[str, int]
    files_examined: int
    steps_completed: int

    def to_dict(self) -> dict[str, Any]:
        return {
            "dir_name": self.dir_name,
            "timestamp": self.timestamp,
            "lens": self.lens,
            "continuation_id": self.continuation_id,
            "project_name": self.project_name,
            "total_findings": self.total_findings,
            "by_severity": self.by_severity,
            "files_examined": self.files_examined,
            "steps_completed": self.steps_completed,
        }


class HistoryReader:
    """Reader for historical audit data from .optix/history/ directory."""

    def __init__(self, base_dir: Path) -> None:
        """Initialize the HistoryReader.

        Args:
            base_dir: Base directory for history storage (typically .optix/history/)
        """
        self.base_dir = Path(base_dir)

    def list_audits(self) -> list[AuditSummary]:
        """List all audits from history directory.

        Returns:
            List of AuditSummary objects sorted by timestamp (newest first)
        """
        if not self.base_dir.exists():
            return []

        summaries = []
        for audit_dir in self.base_dir.iterdir():
            if not audit_dir.is_dir():
                continue

            audit_file = audit_dir / "audit.json"
            if not audit_file.exists():
                continue

            try:
                with open(audit_file, "r", encoding="utf-8") as f:
                    data = json.load(f)

                summary = AuditSummary(
                    dir_name=audit_dir.name,
                    timestamp=data.get("timestamp", ""),
                    lens=data.get("lens", "unknown"),
                    continuation_id=data.get("continuation_id", ""),
                    project_name=data.get("project", {}).get("name"),
                    total_findings=data.get("summary", {}).get("total_findings", 0),
                    by_severity=data.get("summary", {}).get("by_severity", {}),
                    files_examined=data.get("summary", {}).get("files_examined", 0),
                    steps_completed=data.get("summary", {}).get("steps_completed", 0),
                )
                summaries.append(summary)
            except (json.JSONDecodeError, OSError) as e:
                logger.warning(f"Failed to read audit from {audit_dir}: {e}")
                continue

        summaries.sort(key=lambda s: s.timestamp, reverse=True)
        return summaries

    def get_audit(self, dir_name: str) -> Optional[dict[str, Any]]:
        """Get full audit data by directory name.

        Args:
            dir_name: Name of the audit directory (e.g., '2026-01-29_14-30-45_security')

        Returns:
            Full audit data dictionary or None if not found
        """
        if ".." in dir_name or "/" in dir_name or "\\" in dir_name:
            logger.warning(f"Invalid dir_name: {dir_name}")
            return None

        audit_dir = self.base_dir / dir_name
        if not audit_dir.exists() or not audit_dir.is_dir():
            return None

        audit_file = audit_dir / "audit.json"
        if not audit_file.exists():
            return None

        try:
            with open(audit_file, "r", encoding="utf-8") as f:
                data = json.load(f)
            data["dir_name"] = dir_name
            return data
        except (json.JSONDecodeError, OSError) as e:
            logger.error(f"Failed to read audit {dir_name}: {e}")
            return None
