/**
 * Sub-second path: Template Service match → write index.html (skip V3 planner).
 */
import * as fs from 'fs';
import * as path from 'path';
import { stripExecutionShaping } from './requestIntent.js';
function escapeJsString(value) {
    return String(value || '').replace(/\\/g, '\\\\').replace(/'/g, "\\'");
}
function escapeHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}
function extractPopupMessage(vision) {
    const explicitShown = vision.match(/(?:popup\s+is\s+shown|popup\s+shown|shown|shows?|display(?:s|ed)?)\s*:?\s*["']([^"']+)["']/i);
    if (explicitShown?.[1])
        return explicitShown[1];
    const popupPhrases = [...vision.matchAll(/popup[^"']*(?:message|text|says?|shown|with)\s*:?\s*["']([^"']+)["']/gi)];
    if (popupPhrases.length > 0)
        return popupPhrases[popupPhrases.length - 1][1];
    const quoted = vision.match(/(?:alert|message)\s*(?:with|says?|text|:)\s*["']([^"']+)["']/i);
    if (quoted?.[1])
        return quoted[1];
    if (/\bhello\s*world\b/i.test(vision))
        return 'hello world';
    return 'Hello World';
}
function extractButtonLabel(vision) {
    const label = vision.match(/\blabel\s+["']([^"']+)["']/i)
        || vision.match(/\bbutton(?:\s+(?:text|label|called|named))?\s+["']([^"']+)["']/i);
    if (label?.[1])
        return label[1];
    if (/\bclick\b/i.test(vision))
        return 'CLICK';
    return 'Click';
}
function isSimplePopupButtonPrompt(vision) {
    const text = String(vision || '').toLowerCase();
    return /\b(popup|alert|message)\b/.test(text)
        && /\b(button|click|label)\b/.test(text)
        && /\bhello\s*world\b/.test(text);
}
function exactPopupButtonHtml(vision) {
    const popupMessage = extractPopupMessage(vision);
    const buttonLabel = extractButtonLabel(vision);
    const blue = /\bblue\b/i.test(vision) ? '#0000ff' : '#0a0a1a';
    return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${escapeHtml(buttonLabel)} Popup</title>
  <style>
    * { box-sizing: border-box; }
    body {
      min-height: 100vh;
      margin: 0;
      display: grid;
      place-items: center;
      background: ${blue};
      font-family: Arial, sans-serif;
    }
    button {
      padding: 14px 28px;
      border: 0;
      border-radius: 10px;
      background: #ffffff;
      color: #0000aa;
      font-size: 20px;
      font-weight: 700;
      cursor: pointer;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
    }
  </style>
</head>
<body>
  <button id="vigthoria-popup-button" type="button">${escapeHtml(buttonLabel)}</button>
  <script>
    document.getElementById('vigthoria-popup-button').addEventListener('click', function () {
      alert('${escapeJsString(popupMessage)}');
    });
  </script>
</body>
</html>
`;
}
function ensurePopupScript(html, vision) {
    const text = String(vision || '').toLowerCase();
    if (!/\b(popup|alert|hello\s*world)\b/.test(text)) {
        return html;
    }
    if (isSimplePopupButtonPrompt(vision)) {
        return exactPopupButtonHtml(vision);
    }
    if (/\balert\s*\(/i.test(html)) {
        return html;
    }
    const script = `<script>document.addEventListener('DOMContentLoaded',()=>{const b=document.querySelector('button,a.cta,.cta');if(b)b.addEventListener('click',()=>alert('${escapeJsString(extractPopupMessage(vision))}'));});</script>`;
    if (/<\/body>/i.test(html)) {
        return html.replace(/<\/body>/i, `${script}\n</body>`);
    }
    return `${html}\n${script}`;
}
function minimalHelloWorldHtml(popupMessage = 'Hello World') {
    const safe = escapeJsString(popupMessage || 'Hello World');
    return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hello World</title>
  <style>
    body { font-family: system-ui, sans-serif; display: grid; place-items: center; min-height: 100vh; margin: 0; background: #0a0a1a; color: #e6f0ff; }
    h1 { font-size: 2rem; }
  </style>
</head>
<body>
  <h1>Hello World</h1>
  <button type="button" onclick="alert('${safe}')">CLICK</button>
</body>
</html>
`;
}
async function fetchTemplateMatch(api, vision, timeoutMs = 15000) {
    const bases = api.getTemplateServiceBaseUrls();
    let lastError = 'Template Service unreachable';
    for (const base of bases) {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), timeoutMs);
        try {
            const response = await fetch(`${base}/match`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ vision }),
                signal: controller.signal,
            });
            clearTimeout(timer);
            const payload = await response.json().catch(() => null);
            if (!response.ok) {
                lastError = payload?.error || `HTTP ${response.status} from ${base}`;
                continue;
            }
            if (!payload?.success || !payload?.html) {
                lastError = payload?.message || payload?.error || 'No template match';
                continue;
            }
            const templateMeta = payload.template;
            const templateName = typeof templateMeta === 'string'
                ? templateMeta
                : (templateMeta?.name || templateMeta?.id);
            return {
                html: String(payload.html),
                template: templateName,
                confidence: Number(payload.confidence) || 0,
                processingMs: Number(payload.processing_time || payload.processingTime) || 0,
            };
        }
        catch (err) {
            clearTimeout(timer);
            lastError = err?.message || String(err);
        }
    }
    return { error: lastError };
}
export async function runTemplateInstantPath(api, vision, workspacePath, options = {}) {
    const entryPath = options.entryPath || 'index.html';
    const target = path.join(workspacePath, entryPath);
    const cleanVision = stripExecutionShaping(vision);
    const preferMinimal = options.forceMinimalFallback === true;
    let html;
    let usedFallback = false;
    let match = {};
    if (preferMinimal) {
        html = minimalHelloWorldHtml(extractPopupMessage(cleanVision));
        usedFallback = true;
    }
    else {
        match = await fetchTemplateMatch(api, cleanVision);
        html = match.html;
        if (!html && options.allowFallback !== false) {
            html = minimalHelloWorldHtml(extractPopupMessage(cleanVision));
            usedFallback = true;
        }
    }
    if (!html) {
        return { ok: false, error: match.error || 'Template match failed' };
    }
    html = ensurePopupScript(html, cleanVision);
    fs.mkdirSync(path.dirname(target), { recursive: true });
    fs.writeFileSync(target, html, 'utf8');
    return {
        ok: true,
        entryPath,
        templateName: match.template || (usedFallback ? 'minimal-hello-world' : undefined),
        confidence: match.confidence,
        processingMs: match.processingMs,
        usedFallback,
    };
}
