const LANGUAGE_MAP: Record<string, string> = {
  js: "javascript", ts: "typescript", tsx: "typescript", jsx: "javascript",
  py: "python", rb: "ruby", go: "go", rs: "rust", java: "java", php: "php",
  cs: "csharp", cpp: "cpp", c: "c", sh: "bash", bash: "bash", sql: "sql",
  html: "html", css: "css", json: "json", yaml: "yaml", yml: "yaml", xml: "xml",
};

export function getLanguageFromFile(filename: string | null | undefined): string | null {
  if (!filename) return null;
  const ext = filename.split(".").pop()?.toLowerCase();
  return ext ? LANGUAGE_MAP[ext] || null : null;
}

export function getSeverityDot(severity: string): string {
  switch (severity) {
    case "critical": return "bg-red-500";
    case "high": return "bg-orange-500";
    case "medium": return "bg-yellow-500";
    default: return "bg-blue-500";
  }
}

import type { Vulnerability } from "@/types/issues";

export function buildMarkdown(v: Vulnerability): string {
  const parts: string[] = [];
  parts.push(`# ${v.title}`);
  parts.push("");
  const cwePart = v.cwe && v.cwe.length > 0 ? ` · **CWE:** ${v.cwe.join(", ")}` : "";
  parts.push(`**Severity:** ${v.severity.toUpperCase()}${v.cvss ? ` · **CVSS:** ${v.cvss}` : ""}${v.cve ? ` · **CVE:** ${v.cve}` : ""}${cwePart}${v.fix_effort ? ` · **Fix Effort:** ${v.fix_effort}` : ""}`);
  parts.push(`**Status:** ${v.status}`);
  if (v.target) parts.push(`**Target:** ${v.target}`);
  if (v.endpoint) parts.push(`**Endpoint:** ${v.method ? `${v.method} ` : ""}${v.endpoint}`);
  parts.push("");
  if (v.description) {
    parts.push("## Description");
    parts.push("");
    parts.push(v.description);
    parts.push("");
  }
  if (v.impact) {
    parts.push("## Impact");
    parts.push("");
    parts.push(v.impact);
    parts.push("");
  }
  if (v.evidence) {
    parts.push("## Evidence");
    parts.push("");
    parts.push(v.evidence);
    parts.push("");
  }
  if (v.assumptions) {
    parts.push("## Assumptions");
    parts.push("");
    parts.push(v.assumptions);
    parts.push("");
  }
  if (v.technical_analysis) {
    parts.push("## Technical Details");
    parts.push("");
    parts.push(v.technical_analysis);
    parts.push("");
  }
  if (v.remediation_steps) {
    parts.push("## How to Fix");
    parts.push("");
    parts.push(v.remediation_steps);
    parts.push("");
  }
  if (v.poc_description) {
    parts.push("## Proof of Concept");
    parts.push("");
    parts.push(v.poc_description);
    if (v.poc_script_code) {
      parts.push("");
      parts.push("```");
      parts.push(v.poc_script_code);
      parts.push("```");
    }
    parts.push("");
  }
  if (v.code_locations?.length) {
    parts.push("## Code Locations");
    parts.push("");
    if (v.location_meta) {
      parts.push(`**Repository:** ${v.location_meta.repo_url} (${v.location_meta.branch})`);
      parts.push("");
    }
    for (const loc of v.code_locations) {
      if (!loc.file) continue;
      const lineRef = loc.end_line && loc.end_line !== loc.start_line
        ? `${loc.file}:${loc.start_line}-${loc.end_line}`
        : `${loc.file}:${loc.start_line}`;
      parts.push(`### \`${lineRef}\``);
      if (loc.label) parts.push(loc.label);
      if (loc.snippet) {
        parts.push("");
        parts.push("```");
        parts.push(loc.snippet);
        parts.push("```");
      }
      if (loc.fix_before && loc.fix_after) {
        parts.push("");
        parts.push("```diff");
        for (const l of loc.fix_before.split("\n")) parts.push(`- ${l}`);
        for (const l of loc.fix_after.split("\n")) parts.push(`+ ${l}`);
        parts.push("```");
      }
      parts.push("");
    }
  } else if (v.code_file && (v.code_before || v.code_after)) {
    parts.push("## Code");
    parts.push("");
    parts.push(`**File:** \`${v.code_file}\``);
    if (v.code_before && v.code_after) {
      parts.push("");
      parts.push("```diff");
      for (const l of v.code_before.split("\n")) parts.push(`- ${l}`);
      for (const l of v.code_after.split("\n")) parts.push(`+ ${l}`);
      parts.push("```");
    } else if (v.code_diff) {
      parts.push("");
      parts.push("```diff");
      parts.push(v.code_diff);
      parts.push("```");
    }
    parts.push("");
  }
  return parts.join("\n");
}

export function buildAIFixPrompt(v: Vulnerability): string {
  const parts: string[] = [];
  parts.push("This is a security vulnerability found during a code review.");
  parts.push("");
  parts.push(`Vulnerability: ${v.title}`);
  parts.push(`Severity: ${v.severity.toUpperCase()}`);
  if (v.cwe && v.cwe.length > 0) {
    parts.push(`CWE: ${v.cwe.join(", ")}`);
  }
  parts.push("");
  parts.push(v.description);

  if (v.evidence) {
    parts.push("");
    parts.push("Evidence:");
    parts.push(v.evidence);
  }

  const allLocations = v.code_locations || [];
  for (const fixLoc of allLocations) {
    if (!fixLoc.file) continue;
    const startLine = fixLoc.start_line || 0;
    const endLine = fixLoc.end_line || startLine;
    parts.push("");
    parts.push(`Location: ${fixLoc.file}:${startLine}-${endLine}`);
    if (fixLoc.label) {
      parts.push(`Context: ${fixLoc.label}`);
    }
    if (fixLoc.fix_before && fixLoc.fix_after) {
      parts.push("```");
      parts.push(`// Before:\n${fixLoc.fix_before}`);
      parts.push(`// After:\n${fixLoc.fix_after}`);
      parts.push("```");
    } else if (fixLoc.snippet) {
      parts.push("```");
      parts.push(fixLoc.snippet);
      parts.push("```");
    }
  }

  if (v.remediation_steps) {
    parts.push("");
    parts.push("How to fix:");
    parts.push(v.remediation_steps);
  }
  parts.push("");
  parts.push("Please fix this vulnerability. If you propose a fix, make it concise and minimal.");
  return parts.join("\n");
}

export async function copyToClipboard(text: string): Promise<void> {
  try {
    await navigator.clipboard.writeText(text);
  } catch {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.style.position = "absolute";
    ta.style.left = "-9999px";
    document.body.appendChild(ta);
    ta.select();
    document.execCommand("copy");
    document.body.removeChild(ta);
  }
}
