"""Custom certificate file scanner for quantum vulnerability detection."""

import re
import logging
from pathlib import Path
from typing import List, Dict, Any

logger = logging.getLogger(__name__)

CERT_RULES = [
    {
        "id": "cert-weak-rsa-signature",
        "pattern": re.compile(r"sha(?:1|256|384|512)WithRSAEncryption|md5WithRSAEncryption", re.IGNORECASE),
        "message": "Certificate uses RSA signature algorithm which is quantum-vulnerable. Migrate to a post-quantum algorithm.",
        "severity": "ERROR",
        "metadata": {"quantum_vulnerable": True, "quantum_risk_score": 90},
    },
    {
        "id": "cert-weak-ecc-signature",
        "pattern": re.compile(r"ecdsa-with-SHA(?:256|384|512)|ecPublicKey", re.IGNORECASE),
        "message": "Certificate uses ECDSA/ECC which is quantum-vulnerable. Migrate to a post-quantum algorithm.",
        "severity": "ERROR",
        "metadata": {"quantum_vulnerable": True, "quantum_risk_score": 85},
    },
    {
        "id": "cert-weak-dsa-signature",
        "pattern": re.compile(r"dsaWithSHA|id-dsa", re.IGNORECASE),
        "message": "Certificate uses DSA which is quantum-vulnerable. Migrate to a post-quantum algorithm.",
        "severity": "ERROR",
        "metadata": {"quantum_vulnerable": True, "quantum_risk_score": 90},
    },
    {
        "id": "cert-rsa-oid",
        "pattern": re.compile(r"1\.2\.840\.113549\.1\.1\.(?:1|4|5|11|12|13|14)"),
        "message": "Certificate OID indicates RSA key or RSA-based signature — quantum-vulnerable.",
        "severity": "ERROR",
        "metadata": {"quantum_vulnerable": True, "quantum_risk_score": 90},
    },
    {
        "id": "cert-ecc-oid",
        "pattern": re.compile(r"1\.2\.840\.10045\.(?:2\.1|4\.3\.[12347])"),
        "message": "Certificate OID indicates ECC key or ECDSA signature — quantum-vulnerable.",
        "severity": "ERROR",
        "metadata": {"quantum_vulnerable": True, "quantum_risk_score": 85},
    },
]


class CertificateCryptoScanner:
    def scan_file(self, file_path: str) -> List[Dict[str, Any]]:
        try:
            content = Path(file_path).read_text(encoding="utf-8", errors="replace")
        except Exception as e:
            logger.warning(f"Could not read certificate file {file_path}: {e}")
            return []

        findings = []
        lines = content.splitlines()
        seen: set = set()  # deduplicate same rule on same line

        for rule in CERT_RULES:
            for line_no, line in enumerate(lines, start=1):
                if rule["pattern"].search(line):
                    key = (rule["id"], line_no)
                    if key in seen:
                        continue
                    seen.add(key)
                    findings.append({
                        "rule_id": rule["id"],
                        "message": rule["message"],
                        "severity": rule["severity"],
                        "line": line_no,
                        "line_content": line.strip(),
                        "metadata": rule["metadata"],
                    })

        return findings

    def format_findings(self, findings: List[Dict[str, Any]], file_path: str = "") -> Dict[str, Any]:
        results = []
        for f in findings:
            results.append({
                "check_id": f"custom-rules.certificate.security.quantum-crypto-vulnerabilities.{f['rule_id']}",
                "path": file_path,
                "start": {"line": f["line"], "col": 1},
                "end": {"line": f["line"], "col": 1},
                "extra": {
                    "message": f["message"],
                    "severity": f["severity"],
                    "metadata": f["metadata"],
                    "lines": f["line_content"],
                },
            })
        return {"results": results}
