import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const TRANSCRIPT_DIR = path.join(__dirname, '..', '..', '..', 'data', 'transcripts');

// Sanitize patterns — hide payment/contact info
const REDACT_PATTERNS = [
  { name: 'qris',  re: /\b\d{6,18}\b/g, replace: '[QRIS-REDACTED]' },        // long digit strings
  { name: 'email', re: /[\w.+-]+@[\w-]+\.[\w.-]+/g, replace: '[EMAIL]' },
  { name: 'phone', re: /\b(?:\+?62|0)[\d\s-]{8,14}\b/g, replace: '[PHONE]' },
  { name: 'token', re: /\b[A-Za-z0-9_-]{32,}\b/g, replace: '[TOKEN]' },
];

function sanitize(text) {
  if (!text) return '';
  let out = text;
  for (const p of REDACT_PATTERNS) out = out.replace(p.re, p.replace);
  return out;
}

function escape(s) {
  return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}

export async function generateTranscript(channel, ticket) {
  await mkdir(TRANSCRIPT_DIR, { recursive: true });
  const messages = [];
  let before;
  for (let i = 0; i < 10; i++) {
    const batch = await channel.messages.fetch({ limit: 100, before }).catch(() => null);
    if (!batch || batch.size === 0) break;
    messages.push(...batch.values());
    before = batch.last()?.id;
    if (batch.size < 100) break;
  }
  messages.reverse();

  const html = `<!DOCTYPE html>
<html><head><meta charset="utf-8">
<title>Ticket #${ticket.id} Transcript</title>
<style>
  body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#1e1f22;color:#dbdee1;margin:0;padding:20px}
  .header{background:#2b2d31;padding:16px;border-radius:8px;margin-bottom:16px}
  .header h1{margin:0 0 8px;font-size:20px;color:#fff}
  .header .meta{color:#949ba4;font-size:13px}
  .msg{padding:8px 12px;margin:4px 0;border-radius:4px;display:flex;gap:12px}
  .msg:hover{background:#2e3035}
  .avatar{width:40px;height:40px;border-radius:50%;background:#5865f2;flex-shrink:0;display:grid;place-items:center;color:#fff;font-weight:600}
  .body{flex:1;min-width:0}
  .author{font-weight:600;color:#fff}
  .time{color:#949ba4;font-size:12px;margin-left:8px}
  .content{margin-top:2px;white-space:pre-wrap;word-wrap:break-word}
  .attach{margin-top:6px;padding:6px 10px;background:#2b2d31;border-radius:4px;font-size:12px;color:#949ba4}
  .footer{margin-top:24px;text-align:center;color:#949ba4;font-size:11px}
</style></head>
<body>
<div class="header">
  <h1>🎫 Ticket #${ticket.id}</h1>
  <div class="meta">
    Channel: #${escape(channel.name)} ·
    Category: ${escape(ticket.category || '-')} ·
    Opened: ${new Date(ticket.created_at * 1000).toLocaleString()} ·
    Closed: ${new Date().toLocaleString()}
  </div>
</div>
<div class="messages">
${messages.map(m => `
  <div class="msg">
    <div class="avatar">${escape((m.author.username[0] || '?').toUpperCase())}</div>
    <div class="body">
      <span class="author">${escape(m.author.username)}</span>
      <span class="time">${new Date(m.createdTimestamp).toLocaleString()}</span>
      ${m.content ? `<div class="content">${escape(sanitize(m.content))}</div>` : ''}
      ${m.attachments.size ? `<div class="attach">📎 ${m.attachments.size} attachment(s) — [REDACTED]</div>` : ''}
    </div>
  </div>
`).join('\n')}
</div>
<div class="footer">Generated by HaikzBot · ${messages.length} messages · Sensitive data redacted</div>
</body></html>`;

  const filePath = path.join(TRANSCRIPT_DIR, `ticket-${ticket.id}.html`);
  await writeFile(filePath, html, 'utf8');
  return filePath;
}
