import { readFileSync, existsSync } from "fs";
import { join } from "path";
import { NextRequest } from "next/server";
import { getGhlDemoData } from "@/lib/ghl-demo-data";
import { getCustomAppData } from "@/app/api/app-data/route";

// Map app IDs to filenames (must stay in sync with chat/route.ts)
const APP_NAME_MAP: Record<string, string> = {
  // n8n apps — mapped to actual built files in n8n-mcp-apps/dist/app-ui/
  "n8n-workflow-builder": "workflow-builder",
  "n8n-workflow-dashboard": "workflow-dashboard",
  "n8n-execution-monitor": "execution-dashboard",
  "n8n-node-config": "node-explorer",
  "n8n-node-explorer": "node-explorer",
  "n8n-template-gallery": "template-gallery",
  "n8n-health-monitor": "health-monitor",
  "n8n-webhook-tester": "workflow-tester",
  "n8n-workflow-templates": "template-gallery",
  "n8n-workflow-detail": "workflow-detail",
  // competitor research apps
  "competitor-intake-form": "intake-form",
  "competitor-dashboard": "dashboard",
  // Reonomy apps
  "reonomy-search-builder": "reonomy-search-builder",
  "reonomy-results-viewer": "reonomy-results-viewer",
  "reonomy-dashboard": "reonomy-dashboard",
  // GHL apps — all 65
  "ghl-affiliate-dashboard": "affiliate-dashboard",
  "ghl-agent-stats": "agent-stats",
  "ghl-appointment-booker": "appointment-booker",
  "ghl-appointment-detail": "appointment-detail",
  "ghl-blog-manager": "blog-manager",
  "ghl-calendar-resources": "calendar-resources",
  "ghl-calendar-view": "calendar-view",
  "ghl-call-detail": "call-detail",
  "ghl-call-log": "call-log",
  "ghl-campaign-stats": "campaign-stats",
  "ghl-company-detail": "company-detail",
  "ghl-company-list": "company-list",
  "ghl-contact-card": "contact-card",
  "ghl-contact-creator": "contact-creator",
  "ghl-contact-grid": "contact-grid",
  "ghl-contact-timeline": "contact-timeline",
  "ghl-conversation-list": "conversation-list",
  "ghl-conversation-thread": "conversation-thread",
  "ghl-coupon-manager": "coupon-manager",
  "ghl-course-catalog": "course-catalog",
  "ghl-course-detail": "course-detail",
  "ghl-custom-fields-manager": "custom-fields-manager",
  "ghl-duplicate-checker": "duplicate-checker",
  "ghl-email-template-preview": "email-template-preview",
  "ghl-estimate-builder": "estimate-builder",
  "ghl-estimate-preview": "estimate-preview",
  "ghl-form-list": "form-list",
  "ghl-form-submissions": "form-submissions",
  "ghl-free-slots-finder": "free-slots-finder",
  "ghl-funnel-detail": "funnel-detail",
  "ghl-funnel-list": "funnel-list",
  "ghl-inventory-dashboard": "inventory-dashboard",
  "ghl-invoice-builder": "invoice-builder",
  "ghl-invoice-list": "invoice-list",
  "ghl-invoice-preview": "invoice-preview",
  "ghl-location-dashboard": "location-dashboard",
  "ghl-media-library": "media-library",
  "ghl-message-composer": "message-composer",
  "ghl-message-detail": "message-detail",
  "ghl-opportunity-card": "opportunity-card",
  "ghl-opportunity-editor": "opportunity-editor",
  "ghl-order-detail": "order-detail",
  "ghl-order-list": "order-list",
  "ghl-pipeline-analytics": "pipeline-analytics",
  "ghl-pipeline-funnel": "pipeline-funnel",
  "ghl-pipeline-kanban": "pipeline-kanban",
  "ghl-product-catalog": "product-catalog",
  "ghl-product-detail": "product-detail",
  "ghl-revenue-dashboard": "revenue-dashboard",
  "ghl-reviews-dashboard": "reviews-dashboard",
  "ghl-smartlist-viewer": "smartlist-viewer",
  "ghl-social-accounts": "social-accounts",
  "ghl-social-calendar": "social-calendar",
  "ghl-social-post-composer": "social-post-composer",
  "ghl-subscription-manager": "subscription-manager",
  "ghl-survey-list": "survey-list",
  "ghl-survey-submissions": "survey-submissions",
  "ghl-tags-manager": "tags-manager",
  "ghl-task-board": "task-board",
  "ghl-team-management": "team-management",
  "ghl-template-library": "template-library",
  "ghl-transaction-list": "transaction-list",
  "ghl-user-detail": "user-detail",
  "ghl-workflow-detail": "workflow-detail",
  "ghl-workflow-status": "workflow-status",
  // Legacy GHL aliases
  "ghl-pipeline-board": "pipeline-board",
  "ghl-quick-book": "quick-book",
  // Google Ads apps
  "google-ads-campaign-dashboard": "campaign-dashboard",
  "google-ads-performance-overview": "performance-overview",
  "google-ads-keyword-analyzer": "keyword-analyzer",
  "google-ads-budget-optimizer": "budget-optimizer",
  "google-ads-search-terms": "search-terms",
  "google-ads-campaign-detail": "campaign-detail",
  "google-ads-recommendations": "recommendations",
  // Meta Ads apps
  "meta-ads-campaign-dashboard": "campaign-dashboard",
  "meta-ads-performance-heatmap": "performance-heatmap",
  "meta-ads-audience-builder": "audience-builder",
  "meta-ads-creative-preview": "creative-preview",
  "meta-ads-funnel-analyzer": "funnel-analyzer",
  "meta-ads-spend-tracker": "spend-tracker",
  "meta-ads-ad-performance-grid": "ad-performance-grid",
  "meta-ads-ab-test-results": "ab-test-results",
  "meta-ads-account-health": "account-health",
  "meta-ads-campaign-builder": "campaign-builder",
  "meta-ads-ad-library-browser": "ad-library-browser",
  // Google Console apps
  "gsc-performance-dashboard": "dashboard",
  "gsc-quick-wins-board": "quick-wins",
  "gsc-url-health-inspector": "url-health",
  "gsc-cannibalization-map": "cannibalization",
  "gsc-content-decay-tracker": "content-decay",
  // Twilio apps
  "twilio-dashboard": "dashboard",
  "twilio-campaign-live": "campaign-live",
  "twilio-conversation-thread": "conversation-thread",
  "twilio-message-log": "message-log",
  "twilio-call-analytics": "call-analytics",
  "twilio-deep-scan-report": "deep-scan-report",
  "twilio-batch-validate": "batch-validate",
  "twilio-number-hunt": "number-hunt",
  "twilio-number-inventory": "number-inventory",
  "twilio-flow-diagram": "flow-diagram",
  "twilio-flow-list": "flow-list",
  "twilio-agent-status": "agent-status",
  "twilio-queue-manager": "queue-manager",
  "twilio-inbox": "inbox",
  "twilio-cost-report": "cost-report",
  "twilio-health-check": "health-check",
  "twilio-error-log": "error-log",
  "twilio-deploy-status": "deploy-status",
  "twilio-compliance-check": "compliance-check",
};

// Directories to search for MCP app HTML files (all MCP servers)
// Order matters: first match wins. React GHL apps checked first for consistency.
const APP_DIRS = [
  // n8n apps (flat HTML)
  join(process.cwd(), "../n8n-mcp-apps/dist/app-ui"),
  // Competitor research apps (flat HTML)
  join(process.cwd(), "../competitor-research-mcp/dist/app-ui"),
  // GHL React apps (subdirectory format — 65 apps, consistent styling)
  join(process.cwd(), "../mcp-diagrams/GoHighLevel-MCP/src/ui/dist/apps"),
  // GHL legacy template apps (flat HTML fallback)
  join(process.cwd(), "../mcp-diagrams/GoHighLevel-MCP/dist/app-ui"),
  join(process.cwd(), "../mcp-diagrams/ghl-mcp-apps-only/dist/app-ui"),
  // Google Ads apps (static HTML demos)
  join(process.cwd(), "../mcp-diagrams/google-ads-mcp/dist/app-ui"),
  // Meta Ads apps (static HTML demos)
  join(process.cwd(), "../meta-ads-mcp/dist/app-ui"),
  // Google Search Console apps (static HTML demos)
  join(process.cwd(), "../google-console-mcp/dist/app-ui"),
  // Twilio apps (static HTML demos)
  join(process.cwd(), "../twilio-mcp/dist/app-ui"),
  // Reonomy apps (CRE data)
  join(process.cwd(), "../reonomy-mcp/dist/app-ui"),
];

function resolveAppPath(appId: string): string | null {
  const appFileName = APP_NAME_MAP[appId] || appId;
  for (const dir of APP_DIRS) {
    // Check flat format: {dir}/{appFileName}.html
    const flatPath = join(dir, `${appFileName}.html`);
    if (existsSync(flatPath)) return flatPath;

    // Check subdirectory format: {dir}/{appFileName}/index.html
    const subDirPath = join(dir, appFileName, "index.html");
    if (existsSync(subDirPath)) return subDirPath;
  }
  return null;
}

export async function GET(request: NextRequest) {
  const appId = request.nextUrl.searchParams.get("app");

  if (!appId) {
    return new Response(JSON.stringify({ error: "Missing app parameter" }), {
      status: 400,
      headers: { "Content-Type": "application/json" },
    });
  }

  const appPath = resolveAppPath(appId);

  if (!appPath) {
    return new Response(
      `<html><body style="background:#1a1d23;color:#dcddde;font-family:sans-serif;padding:40px;text-align:center">
        <h2>App Not Found</h2>
        <p>MCP App "${appId}" is not available yet.</p>
      </body></html>`,
      {
        status: 200,
        headers: { "Content-Type": "text/html; charset=utf-8" },
      }
    );
  }

  let html = readFileSync(appPath, "utf-8");

  // Check for custom app data from thread conversations FIRST
  // If a thread has generated custom data, use it instead of demo data
  const customData = getCustomAppData(appId);

  if (customData) {
    // Thread-customized data takes priority over demo data
    const injection = `<script>window.__MCP_APP_DATA__=${JSON.stringify(customData)};</script>`;
    html = html.replace("</head>", `${injection}\n</head>`);
  } else {
    // Fall back to demo data for GHL apps so they render with content
    // instead of showing "Waiting for data..."
    const appFileName = APP_NAME_MAP[appId] || appId;
    const demoData = getGhlDemoData(appFileName);
    if (demoData) {
      const injection = `<script>window.__MCP_APP_DATA__=${JSON.stringify(demoData)};</script>`;
      html = html.replace("</head>", `${injection}\n</head>`);
    }
  }

  return new Response(html, {
    status: 200,
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-cache, no-store, must-revalidate",
    },
  });
}
