import { vigthoriaHttpProxy } from '@/lib/tauri-bridge';
import { GOA_TEMPLATE_CATALOG_V1, getTemplateVariables } from '@/lib/template-catalog';
import type { TemplateCategoryCatalog, TemplateCatalogEntry } from '@/types/goa-orchestrator';

const GOA_CATEGORY_LABELS: Record<string, string> = {
  forms: 'Auth & Forms',
  dashboards: 'DB / Admin CRUD',
  blogs: 'API Docs & Content',
  ecommerce: 'Commerce / Stripe-style',
  funnels: 'Commerce / Stripe-style',
  'landing-pages': 'Greenfield Landing / SaaS',
  business: 'Business / Funnels',
};

const PRIORITY_CATEGORIES = [
  'forms',
  'dashboards',
  'blogs',
  'ecommerce',
  'funnels',
  'landing-pages',
];

interface RemoteTemplate {
  id: string;
  name?: string;
  category?: string;
  description?: string;
  tags?: string[];
  filePath?: string;
}

interface RemoteStats {
  total?: number;
  totalTemplates?: number;
  byCategory?: Record<string, number>;
  categories?: Record<string, number>;
}

function trimBase(url: string, fallback: string): string {
  return (url || '').trim().replace(/\/+$/, '') || fallback;
}

function staticHintsFor(id: string): Pick<TemplateCatalogEntry, 'variables' | 'useWhen'> {
  for (const cat of GOA_TEMPLATE_CATALOG_V1) {
    const hit = cat.templates.find((t) => t.id === id);
    if (hit) return { variables: hit.variables, useWhen: hit.useWhen };
  }
  return { variables: ['TITLE', 'COMPANY_NAME'], useWhen: [] };
}

function inferUseWhen(tpl: RemoteTemplate): string[] {
  const fromTags = (tpl.tags || []).map((t) => t.toLowerCase());
  const fromDesc = (tpl.description || '').toLowerCase().split(/\W+/).filter((w) => w.length > 3);
  return [...new Set([...fromTags, ...fromDesc])].slice(0, 8);
}

/** Pull live template IDs from Template Service; merge with static GOA hints. */
export async function fetchLiveTemplateCatalog(
  templateUrl: string,
  token?: string | null,
): Promise<{ catalog: TemplateCategoryCatalog[]; totalTemplates: number; source: 'live' | 'static' }> {
  const base = trimBase(templateUrl, 'https://coder.vigthoria.io/api/template-service');
  try {
    const [statsRes, templatesRes] = await Promise.all([
      vigthoriaHttpProxy('GET', `${base}/stats`, token ?? null, null),
      vigthoriaHttpProxy('GET', `${base}/templates`, token ?? null, null),
    ]);
    if (!statsRes.ok || !templatesRes.ok) {
      throw new Error('Template service unavailable');
    }
    const statsBody = JSON.parse(statsRes.body) as { stats?: RemoteStats };
    const templatesBody = JSON.parse(templatesRes.body) as {
      templates?: RemoteTemplate[];
      count?: number;
    };
    const templates = templatesBody.templates || [];
    const categoryCounts =
      statsBody.stats?.byCategory ||
      statsBody.stats?.categories ||
      {};

    const grouped = new Map<string, TemplateCatalogEntry[]>();
    for (const cat of PRIORITY_CATEGORIES) {
      grouped.set(cat, []);
    }

    for (const tpl of templates) {
      const cat = tpl.category || 'landing-pages';
      if (!PRIORITY_CATEGORIES.includes(cat)) continue;
      const list = grouped.get(cat) || [];
      if (list.length >= 6) continue;
      const hints = staticHintsFor(tpl.id);
      list.push({
        id: tpl.id,
        category: cat,
        name: (tpl.name || tpl.id).replace(/\{\{TITLE\}\}/g, tpl.id),
        variables: getTemplateVariables(tpl.id).length ? getTemplateVariables(tpl.id) : hints.variables,
        useWhen: hints.useWhen.length ? hints.useWhen : inferUseWhen(tpl),
      });
      grouped.set(cat, list);
    }

    const catalog: TemplateCategoryCatalog[] = PRIORITY_CATEGORIES.filter(
      (cat) => (grouped.get(cat)?.length ?? 0) > 0,
    ).map((cat) => ({
      category: cat,
      label: GOA_CATEGORY_LABELS[cat] || cat,
      count: categoryCounts[cat] ?? grouped.get(cat)?.length ?? 0,
      templates: grouped.get(cat) || [],
    }));

    if (catalog.length === 0) throw new Error('Empty live catalog');
    return {
      catalog,
      totalTemplates:
        statsBody.stats?.total ??
        statsBody.stats?.totalTemplates ??
        templatesBody.count ??
        templates.length,
      source: 'live',
    };
  } catch {
    return {
      catalog: GOA_TEMPLATE_CATALOG_V1,
      totalTemplates: 188,
      source: 'static',
    };
  }
}
