from datetime import datetime

SEVERITY_EMOJI = {
    "ERROR": "🔴",
    "WARNING": "🟡",
    "INFO": "🔵",
    "CRITICAL": "🔴",
    "HIGH": "🔴",
    "MEDIUM": "🟡",
    "LOW": "🔵",
}


def save_report(output_path: str, repo_name: str, repo_url: str, findings: dict, ai_summary: str | None):
    """Generate and save the final Markdown report."""
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    semgrep = findings.get("semgrep", [])
    deps = findings.get("dependencies", [])
    secrets = findings.get("secrets", [])
    total = len(semgrep) + len(deps) + len(secrets)

    lines = []
    lines.append("# RepoSec Security Report")
    lines.append(f"\n**Repository:** [{repo_name}]({repo_url})")
    lines.append(f"**Scanned:** {now}")
    lines.append(f"**Total Issues Found:** {total}")
    lines.append("\n---\n")

    if ai_summary:
        lines.append("## AI Security Analysis\n")
        lines.append(ai_summary)
        lines.append("\n---\n")

    lines.append(f"## Static Analysis ({len(semgrep)} findings)\n")
    if semgrep:
        lines.append("| Severity | File | Line | Issue |")
        lines.append("|----------|------|------|-------|")
        for finding in semgrep:
            severity = finding.get("severity", "WARNING")
            emoji = SEVERITY_EMOJI.get(severity, "⚪")
            rule = finding.get("rule", "").split(".")[-1]
            lines.append(f"| {emoji} {severity} | `{finding['file']}` | {finding['line']} | {rule} |")

        lines.append("\n### Details\n")
        for finding in semgrep[:20]:
            lines.append(f"**{finding.get('rule', 'unknown')}** - `{finding['file']}` line {finding['line']}")
            lines.append(f"\n> {finding.get('message', '')}\n")
            if finding.get("code"):
                lines.append(f"```\n{finding['code']}\n```\n")
    else:
        lines.append("_No static analysis issues found._\n")

    lines.append(f"## Vulnerable Dependencies ({len(deps)} found)\n")
    if deps:
        lines.append("| Package | Ecosystem | CVE | Fix |")
        lines.append("|---------|-----------|-----|-----|")
        for dep in deps:
            fix = ", ".join(dep.get("fix_versions", [])) or "Update ASAP"
            lines.append(f"| `{dep['package']}` | {dep.get('ecosystem', '?')} | {dep['cve']} | {fix} |")
    else:
        lines.append("_No vulnerable dependencies found._\n")

    lines.append(f"\n## Hardcoded Secrets ({len(secrets)} found)\n")
    if secrets:
        lines.append("> ⚠️ **Rotate these credentials immediately if this repo is/was public.**\n")
        lines.append("| Type | File | Line |")
        lines.append("|------|------|------|")
        for secret in secrets:
            lines.append(f"| {secret['type']} | `{secret['file']}` | {secret['line']} |")
    else:
        lines.append("_No hardcoded secrets found._\n")

    lines.append("\n---")
    lines.append("_Generated by [RepoSec](https://github.com/NISTALTALSON/reposec) - Free open source security scanner_")

    with open(output_path, "w", encoding="utf-8") as file:
        file.write("\n".join(lines))
