/**
 * 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 ensurePopupScript(html, vision) {
    const text = String(vision || '').toLowerCase();
    if (!/\b(popup|alert|hello\s*world)\b/.test(text)) {
        return html;
    }
    if (/\balert\s*\(/i.test(html)) {
        return html;
    }
    const script = "<script>window.addEventListener('load',()=>alert('Hello World'));</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 = String(popupMessage || 'Hello World').replace(/\\/g, '\\\\').replace(/'/g, "\\'");
    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>
  <script>window.addEventListener('load', () => alert('${safe}'));</script>
</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 };
}
function extractPopupMessage(vision) {
    const quoted = vision.match(/popup\s+with\s+["']([^"']+)["']/i);
    if (quoted?.[1])
        return quoted[1];
    if (/\bhello\s*world\b/i.test(vision))
        return 'Hello World';
    return 'Hello World';
}
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,
    };
}
