"""FORGE hardening attestation document generator.

Produces a formal attestation document (Markdown + JSON) summarising
what FORGE did during a run: scope, findings, remediation, production
readiness score, NIST SP 800-218A coverage, and validation results.

The attestation is the enterprise buyer's evidence artifact — something
procurement teams can attach to vendor security questionnaires.
"""

from __future__ import annotations

import json
import logging
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from forge.compliance.nist_ssdf import ComplianceReport

logger = logging.getLogger(__name__)

_FORGE_VERSION = "0.3.0"


@dataclass
class AttestationData:
    """Data for generating an attestation document."""

    forge_run_id: str
    repo_url: str
    date: str
    loc_total: int
    file_count: int
    agent_invocations: int
    total_findings: int
    findings_fixed: int
    findings_deferred: int
    overall_score: int
    category_scores: list[dict[str, Any]]
    compliance: ComplianceReport | None
    validation_tests_run: int
    validation_tests_passed: int
    validation_regressions: int
    forge_version: str = _FORGE_VERSION


def generate_attestation_markdown(data: AttestationData) -> str:
    """Generate attestation as a Markdown document."""
    fix_rate = (
        f"{data.findings_fixed / data.total_findings * 100:.1f}%"
        if data.total_findings > 0
        else "N/A"
    )

    lines: list[str] = [
        "# FORGE Hardening Attestation",
        "",
        f"**Run ID:** `{data.forge_run_id}`",
        f"**Repository:** {data.repo_url}",
        f"**Date:** {data.date}",
        f"**FORGE Version:** {data.forge_version}",
        "",
        "---",
        "",
        "## 1. Scope",
        "",
        f"| Metric | Value |",
        f"|--------|-------|",
        f"| Lines of Code | {data.loc_total:,} |",
        f"| Files Analyzed | {data.file_count:,} |",
        f"| Agent Invocations | {data.agent_invocations:,} |",
        "",
        "---",
        "",
        "## 2. Findings & Remediation",
        "",
        f"| Metric | Value |",
        f"|--------|-------|",
        f"| Total Findings | {data.total_findings} |",
        f"| Findings Fixed | {data.findings_fixed} |",
        f"| Findings Deferred | {data.findings_deferred} |",
        f"| Fix Success Rate | {fix_rate} |",
        "",
        "---",
        "",
        "## 3. Production Readiness",
        "",
        f"**Overall Score: {data.overall_score}/100**",
        "",
    ]

    if data.category_scores:
        lines.extend([
            "| Category | Score | Weight |",
            "|----------|-------|--------|",
        ])
        for cs in data.category_scores:
            name = cs.get("name", "")
            score = cs.get("score", 0)
            weight = cs.get("weight", 0)
            lines.append(f"| {name} | {score}/100 | {weight:.0%} |")
        lines.append("")

    lines.extend([
        "---",
        "",
        "## 4. NIST SP 800-218A (SSDF) Coverage",
        "",
    ])

    if data.compliance:
        lines.append(data.compliance.to_markdown())
    else:
        lines.append("*Compliance mapping not available for this run.*")

    lines.extend([
        "",
        "---",
        "",
        "## 5. Validation",
        "",
        f"| Metric | Value |",
        f"|--------|-------|",
        f"| Tests Run | {data.validation_tests_run} |",
        f"| Tests Passed | {data.validation_tests_passed} |",
        f"| Regressions Detected | {data.validation_regressions} |",
        "",
        "---",
        "",
        "## Attestation",
        "",
        "This document attests that the FORGE engine (v{version}) performed "
        "an automated security hardening assessment of the above repository. "
        "All findings, remediation actions, and validation results are "
        "recorded in the FORGE telemetry artifacts for this run.".format(
            version=data.forge_version,
        ),
        "",
        f"*Generated by FORGE v{data.forge_version} on {data.date}*",
    ])

    return "\n".join(lines)


def generate_attestation_json(data: AttestationData) -> dict[str, Any]:
    """Generate attestation as a JSON document."""
    fix_rate = (
        round(data.findings_fixed / data.total_findings * 100, 1)
        if data.total_findings > 0
        else 0.0
    )

    return {
        "forge_version": data.forge_version,
        "forge_run_id": data.forge_run_id,
        "repo_url": data.repo_url,
        "date": data.date,
        "scope": {
            "loc_total": data.loc_total,
            "file_count": data.file_count,
            "agent_invocations": data.agent_invocations,
        },
        "findings": {
            "total": data.total_findings,
            "fixed": data.findings_fixed,
            "deferred": data.findings_deferred,
            "fix_success_rate": fix_rate,
        },
        "production_readiness": {
            "overall_score": data.overall_score,
            "category_scores": data.category_scores,
        },
        "nist_ssdf_compliance": (
            data.compliance.to_dict() if data.compliance else None
        ),
        "validation": {
            "tests_run": data.validation_tests_run,
            "tests_passed": data.validation_tests_passed,
            "regressions": data.validation_regressions,
        },
    }


def save_attestation(
    data: AttestationData, output_dir: Path,
) -> tuple[Path, Path]:
    """Save attestation as both Markdown and JSON.

    Returns (md_path, json_path).
    """
    output_dir.mkdir(parents=True, exist_ok=True)

    md_path = output_dir / "attestation.md"
    md_path.write_text(generate_attestation_markdown(data))

    json_path = output_dir / "attestation.json"
    json_path.write_text(
        json.dumps(generate_attestation_json(data), indent=2, default=str)
    )

    logger.info("Attestation saved: %s, %s", md_path, json_path)
    return md_path, json_path
