import { pad, formatTimeSRT, formatTimeVTT } from "./time.js";
import type { Segment } from "$lib/types/app";

type ExportFormat = "txt" | "md" | "csv" | "html" | "srt" | "vtt";

/**
 * Export transcript in various formats.
 * @param {string} text - Plain text transcript
 * @param {Array<{start: number, end: number, text: string}>} segments - Timed segments
 * @param {string} format - "txt" | "md" | "csv" | "html" | "srt" | "vtt"
 * @returns {string}
 */
export function exportTranscript(
  text: string,
  segments: Segment[],
  format: ExportFormat,
): string {
  switch (format) {
    case "srt":
      return toSRT(segments);
    case "vtt":
      return toVTT(segments);
    case "md":
      return toMarkdown(text, segments);
    case "csv":
      return toCSV(segments);
    case "html":
      return toHTML(text, segments);
    default:
      return text;
  }
}

function toSRT(segments: Segment[]): string {
  if (!segments || segments.length === 0) return "";
  return segments
    .map((seg, i) => {
      return `${i + 1}\n${formatTimeSRT(seg.start)} --> ${formatTimeSRT(seg.end)}\n${seg.text.trim()}\n`;
    })
    .join("\n");
}

function toVTT(segments: Segment[]): string {
  if (!segments || segments.length === 0) return "";
  let out = "WEBVTT\n\n";
  out += segments
    .map((seg, i) => {
      return `${i + 1}\n${formatTimeVTT(seg.start)} --> ${formatTimeVTT(seg.end)}\n${seg.text.trim()}\n`;
    })
    .join("\n");
  return out;
}

function toCSV(segments: Segment[]): string {
  if (!segments || segments.length === 0) return "Start,End,Text\n";
  let csv = "Start,End,Text\n";
  for (const seg of segments) {
    const text = seg.text.trim().replace(/"/g, '""');
    csv += `${seg.start.toFixed(2)},${seg.end.toFixed(2)},"${text}"\n`;
  }
  return csv;
}

function escapeHtml(str: string): string {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function toHTML(text: string, segments: Segment[]): string {
  let html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lumotia Transcript</title>
<style>
  body { font-family: "DM Sans", system-ui, sans-serif; max-width: 700px; margin: 2rem auto; padding: 0 1rem; color: #1a1816; line-height: 1.7; }
  h1 { font-family: "Instrument Serif", Georgia, serif; font-style: italic; }
  .meta { color: #9a9486; font-size: 0.85rem; margin-bottom: 1.5rem; }
  .segment { display: flex; gap: 1rem; padding: 0.4rem 0; }
  .timestamp { color: #9a9486; font-size: 0.8rem; min-width: 3rem; font-variant-numeric: tabular-nums; padding-top: 0.15rem; }
  .text { flex: 1; }
</style>
</head>
<body>
<h1>Transcript</h1>
<p class="meta">${new Date().toLocaleDateString("en-GB")}`;
  if (segments?.length > 0) {
    const dur = segments[segments.length - 1].end;
    html += ` &middot; ${Math.round(dur)}s`;
  }
  html += `</p>\n`;

  if (segments?.length > 0) {
    for (const seg of segments) {
      const mins = Math.floor(seg.start / 60);
      const secs = Math.floor(seg.start % 60);
      html += `<div class="segment"><span class="timestamp">${pad(mins)}:${pad(secs)}</span><span class="text">${escapeHtml(seg.text.trim())}</span></div>\n`;
    }
  } else {
    html += `<p>${escapeHtml(text).replace(/\n/g, "<br>")}</p>`;
  }
  html += `</body></html>`;
  return html;
}

function toMarkdown(text: string, segments: Segment[]): string {
  let md = `# Transcription\n\n`;
  md += `**Date:** ${new Date().toLocaleDateString("en-GB")}\n`;
  if (segments && segments.length > 0) {
    const duration = segments[segments.length - 1].end;
    md += `**Duration:** ${Math.round(duration)}s\n`;
  }
  md += `\n---\n\n`;

  if (segments && segments.length > 0) {
    segments.forEach((seg) => {
      const mins = Math.floor(seg.start / 60);
      const secs = Math.floor(seg.start % 60);
      md += `[${pad(mins)}:${pad(secs)}] ${seg.text.trim()}\n\n`;
    });
  } else {
    md += text;
  }

  return md;
}
