"""Report builder — generates a Markdown fix report (``fix.md``)."""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from pathlib import Path

from secagent.models import PipelineResult, SkippedFix, ValidationResult, VerificationStatus

logger = logging.getLogger(__name__)


def generate_report(result: PipelineResult, output_dir: Path | None = None) -> Path:
    """Write a Markdown report summarising the pipeline run.

    Parameters
    ----------
    result:
        Aggregated pipeline result.
    output_dir:
        Directory to write ``fix.md`` into.  Defaults to the current
        working directory.

    Returns
    -------
    Path
        Absolute path to the generated report.
    """
    output_dir = output_dir or Path.cwd()
    report_path = output_dir / "fix.md"

    lines: list[str] = [
        "# SecAgent Fix Report\n",
        f"**Generated:** {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}  ",
        f"**Target:** `{result.target}`\n",
        "## Summary\n",
        f"| # | Stage | Result | Notes |",
        f"|---|---|---|---|",
        f"| 1 | Scan | {result.total_findings} finding(s) detected | Raw vulnerabilities found across all scanners |",
        f"| 2 | Verification | {result.true_positives} real · {result.false_positives} dismissed | AI verified which findings are genuine issues |",
        f"| 3 | Fix | {result.fixes_applied} fix(es) applied | Patches written directly to source files |",
        f"| 4 | Validation | {result.fixes_validated} fix(es) confirmed safe | AI reviewed each patch before it was applied |",
        "",
    ]

    # ---- Per-finding details ----
    if result.vulnerabilities:
        lines.append("---\n")
        lines.append("## Findings\n")

        for vuln in result.vulnerabilities:
            status_badge = ""
            if vuln.verification == VerificationStatus.FP:
                status_badge = " *(False Positive — skipped)*"
            elif vuln.verification == VerificationStatus.TP:
                status_badge = " *(True Positive)*"

            lines.append(f"### {vuln.description}{status_badge}\n")
            lines.append(f"- **Scanner:** {vuln.scanner}")
            lines.append(f"- **File:** `{vuln.file}`")
            lines.append(f"- **Line:** {vuln.line}")
            lines.append(f"- **Severity:** {vuln.severity.value}")
            lines.append(f"- **Type:** {vuln.vuln_type}")
            lines.append("")

    # ---- Fix details ----
    validated = {v.fix.vulnerability.id: v for v in result.validations}

    if result.fixes:
        lines.append("---\n")
        lines.append("## Fixes Applied\n")

        for fix in result.fixes:
            validation: ValidationResult | None = validated.get(fix.vulnerability.id)
            badge = "✅ Validated" if (validation and validation.valid) else "⚠️ Unvalidated"

            lines.append(f"### {fix.vulnerability.description} — {badge}\n")
            lines.append(f"**File:** `{fix.file}`  ")
            lines.append(f"**Reason:** {fix.reason}\n")

            lines.append("**Original:**")
            lines.append(f"```\n{fix.original_snippet}\n```\n")

            lines.append("**Patched:**")
            lines.append(f"```\n{fix.patched_snippet}\n```\n")

            if validation and not validation.valid:
                lines.append(f"> ⚠️ Validation failed: {validation.reason}\n")

            lines.append("")

    # ---- Not fixed / skipped ----
    if result.skipped_fixes:
        lines.append("---\n")
        lines.append("## Not Fixed\n")
        lines.append("These true positives could not be automatically patched:\n")
        for skip in result.skipped_fixes:
            v = skip.vulnerability
            lines.append(f"### {v.description}\n")
            lines.append(f"- **Scanner:** {v.scanner}")
            lines.append(f"- **File:** `{v.file}`")
            lines.append(f"- **Line:** {v.line}")
            lines.append(f"- **Severity:** {v.severity.value}")
            lines.append(f"- **Reason not fixed:** {skip.reason}")
            lines.append("")

    if not result.vulnerabilities:
        lines.append("---\n")
        lines.append("**No vulnerabilities found.** 🎉\n")

    report_path.write_text("\n".join(lines), encoding="utf-8")
    logger.info("Report written to %s", report_path)
    return report_path
