'use strict';

const FRONTEND_EXT_RE = /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i;
const PDF_EXT_RE = /\.pdf$/i;

const FRONTEND_KEYWORDS_RE = new RegExp([
  '\\b(',
  'website|webpage|web\\s?page|landing\\s?page|homepage|portfolio\\s?(site|website|page)?',
  '|hero\\s?(section|banner|image)|nav(igation)?\\s?bar|gallery|lightbox|carousel',
  '|UI|UX|user\\s?interface|user\\s?experience|front[\\s-]?end|frontend',
  '|stylesheet|stylesheets|responsive\\s?(design|layout)|design\\s?system',
  ')\\b',
].join(''), 'i');
const FRONTEND_NEGATIVE_RE = /\b(schema|algorithm|protocol|api|grpc|sql|migration|pipeline|backend\s?service|microservice)\b/i;

const PDF_KEYWORDS_RE = /\b(?:pdf|portable document|document export|print(?:able)? document|export as pdf|make (?:a )?pdf|generate (?:a )?pdf|render (?:a )?pdf)\b/i;
const PDF_GENERATION_RE = /\b(?:make|generate|create|export|render|design|format|style|polish|typeset|print)\b[\s\S]{0,80}\bpdf\b|\bpdf\b[\s\S]{0,80}\b(?:make|generate|create|export|render|design|format|style|polish|typeset|print)\b/i;
const PDF_INGESTION_RE = /\b(?:read|inspect|summari[sz]e|analy[sz]e|extract|review)\b[\s\S]{0,80}\bpdf\b|\bpdf\b[\s\S]{0,80}\b(?:read|inspect|summari[sz]e|analy[sz]e|extract|review)\b/i;

const MANIFESTS = Object.freeze({
  frontend_design: Object.freeze({
    id: 'frontend_design',
    label: 'Web/UI visual artifact work',
    promptSections: ['frontend-design', 'browser-verification'],
    tools: ['start_static_server', 'check_url', 'browser_screenshot'],
    requiredArtifacts: ['screenshot.desktop', 'screenshot.mobile'],
    completionGate: 'visual_artifact_verified',
  }),
  pdf_document: Object.freeze({
    id: 'pdf_document',
    label: 'PDF document generation and design',
    promptSections: ['document-design', 'pdf-generation', 'pdf-verification'],
    tools: ['make_pdf', 'pdf_info', 'pdf_render_pages', 'pdf_read_pages'],
    requiredArtifacts: ['pdf.file', 'pdf.page_preview'],
    completionGate: 'document_artifact_verified',
  }),
  pdf_ingestion: Object.freeze({
    id: 'pdf_ingestion',
    label: 'PDF ingestion and page inspection',
    promptSections: ['pdf-ingestion'],
    tools: ['pdf_info', 'pdf_read_pages', 'pdf_render_pages'],
    requiredArtifacts: ['pdf.file'],
    completionGate: 'source_document_verified',
  }),
});

function routeArtifactCapabilities({ prompt = '', taskFileHints = [], projectInfo = null } = {}) {
  const hints = Array.isArray(taskFileHints) ? taskFileHints.map(String) : [];
  const text = String(prompt || '');
  const capabilities = [];

  if (detectFrontend(text, hints, projectInfo)) capabilities.push(MANIFESTS.frontend_design);

  if (detectPdf(text, hints)) {
    const mode = detectPdfMode(text, hints);
    capabilities.push(mode === 'ingestion' ? MANIFESTS.pdf_ingestion : MANIFESTS.pdf_document);
  }

  return dedupeCapabilities(capabilities);
}

function detectFrontend(text, hints, projectInfo) {
  if (hints.some((hint) => FRONTEND_EXT_RE.test(hint))) return true;
  if (projectInfo?.framework && /\b(?:react|vue|svelte|astro|next|vite)\b/i.test(projectInfo.framework)) {
    if (FRONTEND_KEYWORDS_RE.test(text)) return true;
  }
  if (!FRONTEND_KEYWORDS_RE.test(text)) return false;
  if (FRONTEND_NEGATIVE_RE.test(text) && !hints.some((hint) => FRONTEND_EXT_RE.test(hint))) return false;
  return true;
}

function detectPdf(text, hints) {
  return hints.some((hint) => PDF_EXT_RE.test(hint)) || PDF_KEYWORDS_RE.test(text);
}

function detectPdfMode(text, hints) {
  if (PDF_GENERATION_RE.test(text)) return 'generation';
  if (hints.some((hint) => PDF_EXT_RE.test(hint)) || PDF_INGESTION_RE.test(text)) return 'ingestion';
  return 'generation';
}

function buildArtifactCapabilityContext(capabilities = []) {
  const routed = dedupeCapabilities(capabilities);
  if (!routed.length) return '';
  const lines = ['# Artifact Capability Routes'];
  lines.push('This task was routed to typed artifact capabilities. Treat their tools and evidence gates as part of the completion contract, not optional suggestions.');
  for (const capability of routed) {
    lines.push('');
    lines.push(`## ${capability.label}`);
    lines.push(`- id: \`${capability.id}\``);
    lines.push(`- use tools: ${capability.tools.map((tool) => `\`${tool}\``).join(', ')}`);
    lines.push(`- required evidence before claiming success: ${capability.requiredArtifacts.map((item) => `\`${item}\``).join(', ')}`);
    lines.push(`- completion gate: \`${capability.completionGate}\``);
  }
  lines.push('');
  lines.push('For generated visual/document artifacts, create or verify the artifact with tools, then inspect the rendered output or report the exact tool-backed blocker.');
  return lines.join('\n');
}

function dedupeCapabilities(capabilities = []) {
  const seen = new Set();
  const out = [];
  for (const capability of capabilities || []) {
    if (!capability?.id || seen.has(capability.id)) continue;
    seen.add(capability.id);
    out.push({ ...capability });
  }
  return out;
}

function hasCapability(capabilities, id) {
  return (capabilities || []).some((capability) => capability?.id === id);
}

module.exports = {
  MANIFESTS,
  routeArtifactCapabilities,
  buildArtifactCapabilityContext,
  hasCapability,
};
