"""Checklist Scanner — evaluates compliance checklists for completeness.

Reads JSON/YAML checklist files and evaluates whether required items
have been completed and documented.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from ..types import ComplianceFinding, ComplianceStatus, Severity


class ChecklistScanner:
    """Scans compliance checklist files for completeness."""

    def __init__(self, target_path: Path) -> None:
        self.target_path = target_path

    def scan(self, checks: list[dict[str, Any]]) -> list[ComplianceFinding]:
        """Evaluate checklist files against required checks.

        Looks for checklist files (JSON format) in the target directory
        and cross-references with required checks.

        Args:
            checks: List of check definitions to evaluate.

        Returns:
            List of findings for incomplete or missing checklist items.
        """
        findings: list[ComplianceFinding] = []

        # Find checklist files
        checklist_data: dict[str, Any] = {}
        checklist_files = list(self.target_path.glob("*checklist*.json"))
        checklist_files.extend(self.target_path.glob("**/*checklist*.json"))

        for cf in checklist_files:
            try:
                data = json.loads(cf.read_text(encoding="utf-8"))
                if isinstance(data, dict):
                    # Merge checklist items
                    for item in data.get("items", []):
                        item_id = item.get("check_id", item.get("id", ""))
                        if item_id:
                            checklist_data[item_id] = item
                elif isinstance(data, list):
                    for item in data:
                        item_id = item.get("check_id", item.get("id", ""))
                        if item_id:
                            checklist_data[item_id] = item
            except (json.JSONDecodeError, PermissionError):
                continue

        for check in checks:
            check_id = check["id"]
            item = checklist_data.get(check_id)

            if item is None:
                # Check not in any checklist
                findings.append(ComplianceFinding(
                    framework=check.get("framework", ""),
                    check_id=check_id,
                    title=check.get("check", ""),
                    status=ComplianceStatus.UNKNOWN,
                    severity=Severity(check.get("severity", "medium")),
                    detail=f"Check '{check_id}' not found in any compliance checklist",
                    corrective_action=check.get("remediation", ""),
                ))
            elif item.get("status") in ("non_compliant", "fail", "failed", "no"):
                findings.append(ComplianceFinding(
                    framework=check.get("framework", ""),
                    check_id=check_id,
                    title=check.get("check", ""),
                    status=ComplianceStatus.NON_COMPLIANT,
                    severity=Severity(check.get("severity", "medium")),
                    detail=f"Check '{check_id}' marked as non-compliant in checklist",
                    evidence=item.get("evidence", ""),
                    corrective_action=check.get("remediation", ""),
                    responsible_person=item.get("responsible_person", ""),
                    notes=item.get("notes", ""),
                ))
            elif item.get("status") in ("partial", "in_progress"):
                findings.append(ComplianceFinding(
                    framework=check.get("framework", ""),
                    check_id=check_id,
                    title=check.get("check", ""),
                    status=ComplianceStatus.PARTIAL,
                    severity=Severity(check.get("severity", "medium")),
                    detail=f"Check '{check_id}' partially compliant — action needed",
                    evidence=item.get("evidence", ""),
                    corrective_action=check.get("remediation", ""),
                    responsible_person=item.get("responsible_person", ""),
                    notes=item.get("notes", ""),
                ))
            # If compliant, no finding generated

        return findings
