#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Patch github_cve_fixes.py with primary-fix selection and stricter verification."""
from __future__ import annotations

import argparse
import re
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path

INSERT = r'''
# Repositories that usually mirror CVE metadata, PoCs, reports or bulk updates.
# Results from these repositories remain visible as mentions, but cannot by
# themselves promote a CVE to verified_fix.
NON_PRODUCT_REPO_RX = re.compile(
    r"(?:^|/)(?:"
    r"cvelistv5|cvelistv5-cveservicesadaptertest|cve[_-]?reports?|"
    r"poc-cve-collection|cve-poc|vulnerability-poc|threatvault|"
    r"linux-cve-announce(?:\\.0)?|linux_security_vulns|"
    r"cve-research|cve-updates|cybervault-cve-intel|"
    r"mitre_mapping_site|web-csirt"
    r")(?:$|[-_/])",
    re.I,
)

GENERIC_UPDATE_RX = re.compile(
    r"\\b(?:sync|bulk|database|dataset|feed|catalog|cvelist|threat[ -]?vault|"
    r"layer updates?|update layers?|base\\.lock|metadata|mirror)\\b",
    re.I,
)


def repository_is_non_product(repository: Any) -> bool:
    return bool(NON_PRODUCT_REPO_RX.search(clean(repository)))


def direct_cve_fix_language(message: Any, cve_id: str) -> bool:
    """Require fix/patch wording to be directly connected to this CVE."""
    text = clean(message)
    escaped = re.escape(cve_id)
    fix = r"(?:fix(?:e[ds])?|patch(?:e[ds])?|patched|backport(?:ed|ing)?)"
    patterns = (
        rf"\\b{fix}\\b[^\\n.]{{0,80}}\\b{escaped}\\b",
        rf"\\b{escaped}\\b[^\\n.]{{0,80}}\\b{fix}\\b",
    )
    return any(re.search(pattern, text, re.I) for pattern in patterns)


def commit_repositories(commit: dict[str, Any]) -> list[str]:
    values = as_list(commit.get("repositories")) + [commit.get("repository")]
    return sorted(unique_strings(values), key=str.casefold)


def preferred_product_repository(commit: dict[str, Any]) -> str:
    repositories = commit_repositories(commit)
    product = [repo for repo in repositories if not repository_is_non_product(repo)]
    if product:
        # Prefer the shortest path as a deterministic proxy for the least
        # nested/mirror-like repository name. The full alternative list remains.
        return sorted(product, key=lambda value: (len(value), value.casefold()))[0]
    return repositories[0] if repositories else ""


def commit_fix_score(commit: dict[str, Any], cve_id: str) -> tuple[int, list[str]]:
    """Score a SHA-deduplicated commit as remediation evidence."""
    message = clean(commit.get("message"))
    repository = preferred_product_repository(commit)
    reasons: list[str] = []
    score = 0

    if not commit.get("explicit_cve_reference") or cve_id.casefold() not in message.casefold():
        return 0, ["no_explicit_cve_in_commit_message"]

    score += 15
    reasons.append("explicit_cve_in_commit_message")

    if direct_cve_fix_language(message, cve_id):
        score += 45
        reasons.append("fix_language_directly_linked_to_cve")
    elif commit.get("fix_language"):
        score += 10
        reasons.append("generic_fix_language")

    if commit.get("security_context"):
        score += 5
        reasons.append("security_context")
    if commit.get("regression_test_language"):
        score += 5
        reasons.append("regression_test_language")

    if repository_is_non_product(repository):
        score -= 60
        reasons.append("non_product_repository")
    else:
        score += 10
        reasons.append("product_or_upstream_repository_candidate")

    if GENERIC_UPDATE_RX.search(message):
        score -= 25
        reasons.append("generic_or_bulk_update_message")

    if len(message) <= 300:
        score += 5
        reasons.append("focused_commit_message")

    return max(0, min(100, score)), reasons


def advisory_commit_shas(references: list[dict[str, Any]]) -> set[str]:
    return {
        clean(item.get("sha")).casefold()
        for item in references
        if isinstance(item, dict)
        and item.get("kind") == "commit_reference"
        and clean(item.get("sha"))
    }


def select_primary_fix(
    cve_id: str,
    advisories: list[dict[str, Any]],
    commits: list[dict[str, Any]],
    issues: list[dict[str, Any]],
    references: list[dict[str, Any]],
) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
    """Return one primary remediation object plus ranked commit candidates."""
    reviewed_versions: list[dict[str, Any]] = []
    for advisory in advisories:
        if advisory.get("advisory_type") != "reviewed":
            continue
        for version in as_list(advisory.get("fixed_versions")):
            if isinstance(version, dict) and clean(version.get("version")):
                reviewed_versions.append({
                    "type": "patched_version",
                    "verification_level": "verified",
                    "score": 100,
                    "cve_id": cve_id,
                    "ghsa_id": clean(advisory.get("ghsa_id")),
                    "advisory_url": clean(advisory.get("url")),
                    "ecosystem": clean(version.get("ecosystem")),
                    "package": clean(version.get("package")),
                    "version": clean(version.get("version")),
                    "reasons": ["reviewed_github_advisory_documents_patched_version"],
                })

    referenced_shas = advisory_commit_shas(references)
    ranked: list[dict[str, Any]] = []
    for commit in commits:
        if not isinstance(commit, dict):
            continue
        score, reasons = commit_fix_score(commit, cve_id)
        sha = clean(commit.get("sha"))
        advisory_reference = bool(sha and sha.casefold() in referenced_shas)
        if advisory_reference:
            score = max(score, 95)
            reasons.append("github_advisory_references_exact_sha")

        repository = preferred_product_repository(commit)
        verification_level = (
            "verified"
            if advisory_reference and direct_cve_fix_language(commit.get("message"), cve_id)
            else "candidate"
            if score >= 60 and direct_cve_fix_language(commit.get("message"), cve_id)
            else "mention"
        )
        ranked.append({
            "type": "commit",
            "verification_level": verification_level,
            "score": score,
            "cve_id": cve_id,
            "repository": repository,
            "repositories": commit_repositories(commit),
            "sha": sha,
            "url": clean(commit.get("url")),
            "message": clean(commit.get("message")),
            "duplicate_count": int(commit.get("duplicate_count", 1) or 1),
            "reasons": unique_strings(reasons),
        })

    ranked.sort(
        key=lambda item: (
            item.get("verification_level") == "verified",
            item.get("verification_level") == "candidate",
            int(item.get("score", 0)),
            clean(item.get("sha")),
        ),
        reverse=True,
    )

    if reviewed_versions:
        reviewed_versions.sort(
            key=lambda item: (
                clean(item.get("package")).casefold(),
                clean(item.get("version")).casefold(),
            )
        )
        return reviewed_versions[0], ranked

    primary_commit = next(
        (item for item in ranked if item.get("verification_level") in {"verified", "candidate"}),
        None,
    )
    return primary_commit, ranked


def strict_remediation_status(
    primary_fix: dict[str, Any] | None,
    advisories: list[dict[str, Any]],
    commits: list[dict[str, Any]],
    issues: list[dict[str, Any]],
    references: list[dict[str, Any]],
    errors: list[str],
) -> tuple[str, str, list[str]]:
    if primary_fix and primary_fix.get("verification_level") == "verified":
        return "verified_fix", "high", unique_strings(primary_fix.get("reasons", []))
    if primary_fix and primary_fix.get("verification_level") == "candidate":
        return "fix_candidate", "medium", unique_strings(primary_fix.get("reasons", []))
    if advisories or commits or issues or references:
        return "mention_only", "low", ["github_mentions_found_without_strictly_verified_fix"]
    if errors:
        return "lookup_error", "unknown", ["lookup_incomplete_due_to_errors"]
    return "no_public_fix_found", "none", ["no_github_evidence_found"]
'''


def replace_function(source: str, name: str, replacement: str) -> str:
    pattern = re.compile(rf"(?ms)^def {re.escape(name)}\(.*?(?=^def |^# -{{5,}}|\Z)")
    match = pattern.search(source)
    if not match:
        raise RuntimeError(f"Function not found: {name}")
    return source[:match.start()] + replacement.lstrip("\n") + "\n\n" + source[match.end():]


def patch_enrich(source: str) -> str:
    old = re.compile(
        r'''(?ms)^    status, confidence, reasons = remediation_status\(\n'''
        r'''        advisories, commits, issues, references, errors\n'''
        r'''    \)\n'''
    )
    replacement = '''    primary_fix, ranked_fix_candidates = select_primary_fix(\n        cve_id, advisories, commits, issues, references\n    )\n    status, confidence, reasons = strict_remediation_status(\n        primary_fix, advisories, commits, issues, references, errors\n    )\n'''
    source, count = old.subn(replacement, source, count=1)
    if count != 1:
        raise RuntimeError("Could not replace remediation classification in enrich_cve")

    needle = '''        "reasons": reasons,\n        "repositories": repositories_from_evidence(all_evidence),\n'''
    replacement2 = '''        "reasons": reasons,\n        "primary_fix": primary_fix,\n        "fix_candidates": [\n            item for item in ranked_fix_candidates\n            if item.get("verification_level") in {"verified", "candidate"}\n        ][:10],\n        "repositories": repositories_from_evidence(all_evidence),\n'''
    if needle not in source:
        raise RuntimeError("Could not find output insertion point in enrich_cve")
    return source.replace(needle, replacement2, 1)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("script", nargs="?", type=Path, default=Path("github_cve_fixes.py"))
    args = parser.parse_args()
    path = args.script.resolve()
    if not path.is_file():
        print(f"ERROR: not found: {path}", file=sys.stderr)
        return 2

    source = path.read_text(encoding="utf-8")
    if "def select_primary_fix(" in source:
        print("ERROR: primary-fix patch appears to be installed already", file=sys.stderr)
        return 2
    if "def as_list(" not in source:
        print("ERROR: hardened parser helpers are missing; run hardening patch first", file=sys.stderr)
        return 2

    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    backup = path.with_name(f"{path.name}.bak-primary-{stamp}")
    shutil.copy2(path, backup)

    marker = "# ---------------------------------------------------------------------------\n# GitHub evidence collectors"
    index = source.find(marker)
    if index < 0:
        print("ERROR: insertion marker not found", file=sys.stderr)
        return 2

    source = source[:index] + INSERT.lstrip("\n") + "\n\n" + source[index:]
    source = patch_enrich(source)

    # Extend parse-error records so their output schema remains uniform.
    source = source.replace(
        '''                    "reasons": ["unexpected_record_shape_or_parser_error"],\n                    "repositories": [],\n''',
        '''                    "reasons": ["unexpected_record_shape_or_parser_error"],\n                    "primary_fix": None,\n                    "fix_candidates": [],\n                    "repositories": [],\n''',
        1,
    )

    path.write_text(source, encoding="utf-8")
    check = subprocess.run(
        [sys.executable, "-m", "py_compile", str(path)],
        capture_output=True,
        text=True,
    )
    if check.returncode != 0:
        shutil.copy2(backup, path)
        print(check.stderr, file=sys.stderr)
        print(f"ERROR: syntax check failed; restored {backup}", file=sys.stderr)
        return 3

    print(f"Updated: {path}")
    print(f"Backup : {backup}")
    print("Syntax : OK")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
