"""Generate parity certificates with evidence for completed validation runs."""
from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from .contracts import (
    GateStatus,
    ProgressiveValidationState,
)

logger = logging.getLogger(__name__)


class ParityCertificate:
    """Generate pass/fail parity certificates with evidence."""

    def generate(
        self,
        state: ProgressiveValidationState,
    ) -> Dict[str, Any]:
        """Generate a parity certificate from a completed validation state.

        Returns a certificate dict with status, evidence, and gate results.
        """
        is_certified = state.overall_status == "certified"
        gates_passed = sum(1 for g in state.gates if g.status == GateStatus.PASSED)
        total_tests = sum(len(g.test_results) for g in state.gates)
        total_failures = sum(
            sum(1 for r in g.test_results if r.status == "fail")
            for g in state.gates
        )
        total_discrepancies = sum(len(g.discrepancies) for g in state.gates)

        gate_evidence = []
        for i, gate in enumerate(state.gates):
            gate_evidence.append({
                "gate_index": i,
                "scope": gate.scope.value,
                "period": gate.period.value,
                "status": gate.status.value,
                "tests_run": len(gate.test_results),
                "tests_passed": sum(1 for r in gate.test_results if r.status == "pass"),
                "tests_failed": sum(1 for r in gate.test_results if r.status == "fail"),
                "discrepancies": len(gate.discrepancies),
                "fix_attempts": gate.fix_attempts,
                "passed_at": gate.passed_at,
                "failed_at": gate.failed_at,
            })

        certificate = {
            "certificate_id": f"cert_{state.state_id}",
            "report_name": state.spec.report_name,
            "source_system": state.spec.source_system,
            "status": "CERTIFIED" if is_certified else "NOT_CERTIFIED",
            "issued_at": datetime.now(timezone.utc).isoformat(),
            "summary": {
                "gates_total": len(state.gates),
                "gates_passed": gates_passed,
                "total_tests": total_tests,
                "total_failures": total_failures,
                "total_discrepancies": total_discrepancies,
                "overall_status": state.overall_status,
            },
            "gate_evidence": gate_evidence,
            "improvement_suggestions": state.improvement_suggestions,
        }

        return certificate

    def to_markdown(self, certificate: Dict[str, Any]) -> str:
        """Render certificate as markdown."""
        status = certificate["status"]
        icon = "PASS" if status == "CERTIFIED" else "FAIL"
        summary = certificate["summary"]

        lines = [
            f"# Parity Certificate: {certificate['report_name']}",
            "",
            f"**Status:** {icon} {status}",
            f"**Issued:** {certificate['issued_at']}",
            f"**Source System:** {certificate['source_system']}",
            "",
            "## Summary",
            f"- Gates: {summary['gates_passed']}/{summary['gates_total']} passed",
            f"- Tests: {summary['total_tests']} run, {summary['total_failures']} failed",
            f"- Discrepancies: {summary['total_discrepancies']} classified",
            "",
            "## Gate Evidence",
            "",
            "| # | Scope | Period | Status | Tests | Passed | Failed |",
            "|---|-------|--------|--------|-------|--------|--------|",
        ]

        for ge in certificate["gate_evidence"]:
            lines.append(
                f"| {ge['gate_index']} | {ge['scope']} | {ge['period']} | "
                f"{ge['status']} | {ge['tests_run']} | {ge['tests_passed']} | "
                f"{ge['tests_failed']} |"
            )

        suggestions = certificate.get("improvement_suggestions", [])
        if suggestions:
            lines.extend(["", "## Improvement Suggestions", ""])
            for s in suggestions:
                sev = s.get("severity", "info")
                lines.append(f"- **[{sev.upper()}]** {s.get('detail', '')} — {s.get('suggestion', '')}")

        return "\n".join(lines)
