import type { TemplateCategoryCatalog } from '@/types/goa-orchestrator';
import variableIndex from '@/lib/template-variable-index.json';

type VarIndex = {
  templates: Record<string, { category: string; variables: string[]; tags: string[] }>;
};

const VAR_INDEX = variableIndex as VarIndex;

export function getTemplateVariables(templateId: string): string[] {
  return VAR_INDEX.templates[templateId]?.variables ?? ['TITLE', 'COMPANY_NAME', 'TAGLINE'];
}

export function resolveTemplateIdFromPrompt(prompt: string): string | null {
  const lower = prompt.toLowerCase();
  for (const [id, meta] of Object.entries(VAR_INDEX.templates)) {
    if (meta.tags.some((tag) => lower.includes(tag.toLowerCase()))) return id;
  }
  for (const cat of GOA_TEMPLATE_CATALOG_V1) {
    for (const tpl of cat.templates) {
      if (tpl.useWhen.some((kw) => lower.includes(kw))) return tpl.id;
    }
  }
  if (/\b(new|create|build|landing|website|page)\b/.test(lower)) return 'hello-world-minimal';
  return null;
}

export function extractVariablesFromPrompt(prompt: string): Record<string, string> {
  const vars: Record<string, string> = {};
  const templateId = resolveTemplateIdFromPrompt(prompt);
  if (templateId) {
    for (const key of getTemplateVariables(templateId)) {
      if (!vars[key]) {
        vars[key] = key === 'TITLE' ? 'Vigthoria Project' : key === 'COMPANY_NAME' ? 'Vigthoria' : '';
      }
    }
  }
  const stripe = prompt.match(/price[_\s-]?id[=:\s]+([a-zA-Z0-9_]+)/i);
  if (stripe) vars.STRIPE_PRICE_ID = stripe[1];
  const company = prompt.match(/(?:company|brand|name)[=:\s]+["']?([^"'\n,]+)/i);
  if (company) vars.COMPANY_NAME = company[1].trim();
  const title = prompt.match(/(?:title|project)[=:\s]+["']?([^"'\n,]+)/i);
  if (title) vars.TITLE = title[1].trim();
  return vars;
}

/** V1.0 — Top template categories for GOA JSON mapping (188 total in service). */
export const GOA_TEMPLATE_CATALOG_V1: TemplateCategoryCatalog[] = [
  {
    category: 'forms',
    label: 'Auth & Forms',
    count: 21,
    templates: [
      {
        id: 'auth-login-signup',
        category: 'forms',
        name: 'Auth Login / Signup',
        variables: ['TITLE', 'COMPANY_NAME', 'TAGLINE', 'CTA_PRIMARY', 'CTA_SECONDARY'],
        useWhen: ['login', 'signup', 'oauth', 'auth', 'session'],
      },
      {
        id: 'contact-form-floating-modern',
        category: 'forms',
        name: 'Contact Form',
        variables: ['TITLE', 'COMPANY_NAME', 'EMAIL', 'PHONE'],
        useWhen: ['contact', 'lead', 'form'],
      },
    ],
  },
  {
    category: 'dashboards',
    label: 'DB / Admin CRUD',
    count: 4,
    templates: [
      {
        id: 'modern-clean',
        category: 'dashboards',
        name: 'Modern Clean Dashboard',
        variables: ['TITLE', 'METRIC_1_VALUE', 'METRIC_2_VALUE', 'METRIC_3_VALUE'],
        useWhen: ['dashboard', 'admin', 'crud', 'analytics'],
      },
      {
        id: 'professional-business',
        category: 'dashboards',
        name: 'Executive Dashboard',
        variables: ['TITLE', 'COMPANY_NAME', 'YEAR'],
        useWhen: ['kpi', 'executive', 'reporting'],
      },
      {
        id: 'celestial-command-dashboard',
        category: 'dashboards',
        name: 'Celestial Command Dashboard',
        variables: ['TITLE', 'HERO_TITLE', 'HERO_SUBTITLE'],
        useWhen: ['cyber', 'command', 'ops'],
      },
    ],
  },
  {
    category: 'blogs',
    label: 'API Docs & Content',
    count: 13,
    templates: [
      {
        id: 'api-docs-developer',
        category: 'blogs',
        name: 'API Developer Docs Hub',
        variables: ['TITLE', 'COMPANY_NAME', 'DESCRIPTION'],
        useWhen: ['api', 'developer', 'docs', 'openapi', 'rest'],
      },
    ],
  },
  {
    category: 'ecommerce',
    label: 'Commerce / Stripe-style',
    count: 17,
    templates: [
      {
        id: 'aether-marketplace',
        category: 'ecommerce',
        name: 'Aether Marketplace',
        variables: ['TITLE', 'COMPANY_NAME', 'CTA_TEXT', 'HERO_TITLE'],
        useWhen: ['shop', 'store', 'products', 'marketplace'],
      },
      {
        id: 'product-grid-shop-cyber',
        category: 'ecommerce',
        name: 'Product Grid Shop Cyber',
        variables: ['TITLE', 'BRAND_NAME', 'CTA_PRIMARY'],
        useWhen: ['product grid', 'catalog', 'ecommerce'],
      },
      {
        id: 'sales-funnel-modern-clean',
        category: 'funnels',
        name: 'Sales Funnel / Checkout',
        variables: ['TITLE', 'COMPANY_NAME', 'CTA_TEXT'],
        useWhen: ['checkout', 'billing', 'stripe', 'payment', 'subscription', 'funnel'],
      },
    ],
  },
  {
    category: 'landing-pages',
    label: 'Greenfield Landing / SaaS',
    count: 31,
    templates: [
      {
        id: 'saas-startup-hero',
        category: 'landing-pages',
        name: 'SaaS Startup Hero',
        variables: ['TITLE', 'TAGLINE', 'HERO_TITLE', 'HERO_SUBTITLE', 'CTA_PRIMARY', 'CTA_SECONDARY'],
        useWhen: ['saas', 'startup', 'landing', 'hero', 'new project'],
      },
      {
        id: 'hello-world-minimal',
        category: 'landing-pages',
        name: 'Hello World Minimal',
        variables: ['TITLE', 'TAGLINE', 'DESCRIPTION'],
        useWhen: ['minimal', 'starter', 'blank', 'greenfield'],
      },
    ],
  },
];
