import "dotenv/config";
import express from "express";
import path from "path";
import fs from "fs";
import { initializeApp, getApps, cert, type ServiceAccount } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
import { getFirestore } from "firebase-admin/firestore";
import { getAgentResponseServer } from "./src/services/agentServiceServer.js";
import { createBridgeRouter } from "./src/services/bridgeRouter.js";
import { createStorefrontRouter } from "./src/services/storefrontRouter.js";
import {
  AUTHORIZED_EMAILS,
  isAllowedOrigin,
  isAuthorizedEmail,
} from "./src/lib/authGate.js";
import { computeB2BKitTiers } from "./src/lib/b2bPricing.js";

function getServerDir(): string {
  return typeof __dirname === "string" ? __dirname : process.cwd();
}

function readFirebaseConfig(): { projectId?: string; firestoreDatabaseId?: string } {
  const serverDir = getServerDir();
  const candidates = [
    path.join(process.cwd(), "firebase-applet-config.json"),
    path.resolve(serverDir, "firebase-applet-config.json"),
    path.resolve(serverDir, "..", "firebase-applet-config.json"),
  ];
  for (const cfgPath of candidates) {
    try {
      if (fs.existsSync(cfgPath)) {
        return JSON.parse(fs.readFileSync(cfgPath, "utf-8"));
      }
    } catch (err) {
      console.warn("Could not read firebase-applet-config.json:", err);
    }
  }
  return {};
}

function parseServiceAccountFromEnv(): ServiceAccount | null {
  const raw = (process.env.FIREBASE_SERVICE_ACCOUNT_JSON || "").trim();
  if (!raw) return null;
  try {
    const jsonText = raw.startsWith("{")
      ? raw
      : Buffer.from(raw, "base64").toString("utf8");
    const parsed = JSON.parse(jsonText) as ServiceAccount;
    if (parsed && typeof parsed === "object" && (parsed as any).client_email && (parsed as any).private_key) {
      return parsed;
    }
  } catch (err) {
    console.warn("Could not parse FIREBASE_SERVICE_ACCOUNT_JSON:", err);
  }
  return null;
}

function initFirebaseAdmin() {
  if (getApps().length > 0) return;
  const cfg = readFirebaseConfig();
  const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT || cfg.projectId;
  const serviceAccount = parseServiceAccountFromEnv();

  if (serviceAccount) {
    initializeApp({
      credential: cert(serviceAccount),
      ...(projectId ? { projectId } : {}),
    });
    return;
  }

  initializeApp(projectId ? { projectId } : undefined);
}

function getFirestoreDb() {
  const cfg = readFirebaseConfig();
  return cfg.firestoreDatabaseId
    ? getFirestore(getApps()[0], cfg.firestoreDatabaseId)
    : getFirestore(getApps()[0]);
}

async function resolveOwnerUid(db: ReturnType<typeof getFirestore>): Promise<string | null> {
  for (const email of AUTHORIZED_EMAILS) {
    try {
      const ownerRecord = await getAuth().getUserByEmail(email);
      if (ownerRecord?.uid) return ownerRecord.uid;
    } catch {
      // Continue checking next authorized owner email
    }
  }
  try {
    const snap = await db.collection("profiles").limit(1).get();
    if (!snap.empty) {
      return snap.docs[0].id;
    }
  } catch {
    return null;
  }
  return null;
}

async function requireStudioOwner(req: express.Request, res: express.Response, next: express.NextFunction) {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      return res.status(401).json({ error: "Authentication required. Missing Bearer token." });
    }
    const idToken = authHeader.slice(7).trim();
    if (!idToken) {
      return res.status(401).json({ error: "Authentication required. Empty Bearer token." });
    }

    const decoded = await getAuth().verifyIdToken(idToken);
    if (!decoded.email_verified || !isAuthorizedEmail(decoded.email)) {
      return res.status(403).json({ error: "Access denied. Account is not an authorized verified studio owner." });
    }

    (req as any).studioUser = decoded;
    return next();
  } catch (err: any) {
    console.warn("Token verification failed on /api/agent/response:", err?.code || err?.message);
    return res.status(401).json({ error: "Invalid or expired authentication session." });
  }
}

function resolveDistDir(): string {
  const serverDir = getServerDir();
  const candidates = [
    path.join(process.cwd(), "dist"),
    path.resolve(serverDir, "dist"),
    path.resolve(serverDir, "..", "dist"),
  ];
  for (const dir of candidates) {
    if (fs.existsSync(path.join(dir, "index.html"))) {
      return dir;
    }
  }
  return path.join(process.cwd(), "dist");
}

async function startServer() {
  initFirebaseAdmin();
  const app = express();
  const rawPort = (process.env.PORT || "").trim();
  const PORT: string | number = rawPort
    ? /^\d+$/.test(rawPort)
      ? Number(rawPort)
      : rawPort
    : 3000;

  // Respect X-Forwarded-For behind Namecheap / Passenger / proxy load balancer
  app.set("trust proxy", 1);

  // Security Headers & Origin Allowlist CORS Middleware (artisan.ljwellness.net & ljwellness.net)
  app.use((req, res, next) => {
    res.setHeader("X-Content-Type-Options", "nosniff");
    res.setHeader("X-Frame-Options", "SAMEORIGIN");
    res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");

    const origin = req.headers.origin;
    if (origin && isAllowedOrigin(origin, process.env.APP_URL)) {
      res.setHeader("Access-Control-Allow-Origin", origin);
      res.setHeader("Vary", "Origin");
      res.setHeader(
        "Access-Control-Allow-Headers",
        "Content-Type, Authorization, X-Bridge-Key, X-Bridge-Timestamp, X-Bridge-Signature",
      );
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
      if (req.method === "OPTIONS") {
        return res.status(204).end();
      }
    } else if (origin && req.path.startsWith("/api/") && req.method === "OPTIONS") {
      return res.status(403).json({ error: "Origin not permitted by studio policy." });
    }
    next();
  });

  app.use(express.json({
    limit: "2mb",
    verify: (req: any, _res, buf) => {
      req.rawBody = buf;
    },
  }));
  app.use(express.urlencoded({ extended: true, limit: "2mb" }));

  // In-memory rate limiter (120 requests per minute per IP)
  const ipRequests = new Map<string, { count: number; resetTime: number }>();
  const rateLimiter = (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const ip = req.ip || req.socket.remoteAddress || 'unknown';
    const now = Date.now();
    const entry = ipRequests.get(ip) || { count: 0, resetTime: now + 60000 };

    if (now > entry.resetTime) {
      entry.count = 1;
      entry.resetTime = now + 60000;
    } else {
      entry.count += 1;
    }

    ipRequests.set(ip, entry);

    if (entry.count > 120) {
      return res.status(429).json({ error: "Rate limit exceeded. Please throttle requests." });
    }
    next();
  };

  // Stricter rate limiter for public inquiry/pre-order intake (10 submissions per 15 mins per IP)
  const inquiryIpRequests = new Map<string, { count: number; resetTime: number }>();
  const inquiryRateLimiter = (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const ip = req.ip || req.socket.remoteAddress || "unknown";
    const now = Date.now();
    const windowMs = 15 * 60 * 1000;
    const entry = inquiryIpRequests.get(ip) || { count: 0, resetTime: now + windowMs };
    if (now > entry.resetTime) {
      entry.count = 1;
      entry.resetTime = now + windowMs;
    } else {
      entry.count += 1;
    }
    inquiryIpRequests.set(ip, entry);
    if (entry.count > 10) {
      return res.status(429).json({ error: "Too many inquiry submissions. Please wait a few minutes before retrying." });
    }
    next();
  };

  // API Route: Health check
  app.get("/api/health", (req, res) => {
    res.json({ 
      status: "healthy", 
      timestamp: new Date().toISOString() 
    });
  });

  // API Route: Public B2B Sample Box & Pre-Order Inquiry Intake
  app.post("/api/inquiries", inquiryRateLimiter, async (req, res) => {
    try {
      const body = req.body || {};
      const companyName = String(body.companyName || "").trim().slice(0, 200);
      const contactPerson = String(body.contactPerson || "").trim().slice(0, 160);
      const email = String(body.email || "").trim().slice(0, 200);
      const phone = String(body.phone || "").trim().slice(0, 60);
      const allowedTypes = [
        "Luxury Builder",
        "Condo Developer",
        "Rental Developer",
        "Realtor",
        "Architecture / Design",
        "Corporate Gifting"
      ];
      const accountType = allowedTypes.includes(body.accountType) ? body.accountType : "Luxury Builder";
      const audienceMode = body.audienceMode === "renter" ? "renter" : "homeowner";
      const language = ["en", "fr", "bilingual"].includes(body.language) ? body.language : "bilingual";
      const unitCount = Math.min(10000, Math.max(1, Math.round(Number(body.unitCount) || 10)));
      const requestType = body.requestType === "sample-box" ? "Sample Specimen Box" : "Pre-Order / Production Run";
      const handoverDate = String(body.handoverDate || "").trim().slice(0, 40);
      const notes = String(body.notes || "").trim().slice(0, 1500);

      if (!companyName || !contactPerson || !email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        return res.status(400).json({
          error: "Please provide company name, contact person, and a valid business email."
        });
      }

      const tiers = computeB2BKitTiers({
        botanicalUnitCost: 14,
        specimenBoxCost: 8.5,
        customBinderPrintCost: 16,
        wholesaleBinderPrintCost: 11,
        qrInsertCardCost: 1.25,
        customAssemblyCost: 6,
        wholesaleAssemblyCost: 2.5,
        overheadPerKit: 12,
        shippingFreightPerKit: 2.25,
        insuranceTestingPerKit: 1.0,
        spoilageBufferPct: 3,
        paymentProcessingPct: 2.9,
        customTargetMarginPct: 75,
        wholesaleFloorMarginPct: 55
      });

      const selectedTier =
        unitCount >= 50
          ? tiers[3]
          : unitCount >= 25
            ? tiers[2]
            : unitCount >= 10
              ? tiers[1]
              : tiers[0];

      const totalEstimate = Number((selectedTier.recommendedPrice * unitCount).toFixed(2));
      const deposit50Pct = Number((totalEstimate * 0.5).toFixed(2));

      const db = getFirestoreDb();
      const ownerUid = await resolveOwnerUid(db);

      if (!ownerUid) {
        return res.status(503).json({
          error: "Studio owner inbox is not initialized yet. Please contact the studio directly."
        });
      }

      const nowIso = new Date().toISOString();
      const today = nowIso.split("T")[0];
      const suffix = Math.random().toString(36).slice(2, 7).toUpperCase();
      const referenceId = `LJW-${today.replace(/-/g, "")}-${suffix}`;
      const accountId = `inq_${Date.now().toString(36)}_${suffix.toLowerCase()}`;
      const taskId = `task_${Date.now().toString(36)}_${suffix.toLowerCase()}`;

      const formattedNotes = [
        `[${requestType}] Ref: ${referenceId}`,
        `Units: ${unitCount} (${selectedTier.name}) | Audience: ${audienceMode === "renter" ? "Resident / Renter (Lease)" : "Condo Buyer / Homeowner"}`,
        `Language Spec: ${language.toUpperCase()} (Loi 96)`,
        `Indicative Quote: $${selectedTier.recommendedPrice.toFixed(2)}/kit · Est. Total $${totalEstimate.toLocaleString()} · 50% Deposit $${deposit50Pct.toLocaleString()}`,
        handoverDate ? `Target Handover: ${handoverDate}` : null,
        notes ? `Project Notes: ${notes}` : null
      ]
        .filter(Boolean)
        .join("\n");

      await db.collection("corporate_accounts").doc(accountId).set({
        id: accountId,
        uid: ownerUid,
        companyName,
        contactPerson,
        email,
        phone,
        accountType,
        nicheFocus: `${selectedTier.name} (${audienceMode})`,
        annualBudgetPotential: totalEstimate,
        status: "Lead",
        notes: formattedNotes,
        createdAt: today,
        updatedAt: today
      });

      await db.collection("tasks").doc(taskId).set({
        id: taskId,
        uid: ownerUid,
        title: `Inbound B2B ${requestType}: ${companyName} (${unitCount} units)`,
        description: `${contactPerson} (${email}${phone ? `, ${phone}` : ""}) submitted an inquiry via the public landing page.\n\n${formattedNotes}`,
        assignedTo: "Business",
        status: "pending",
        priority: "high",
        createdAt: today
      });

      return res.status(201).json({
        ok: true,
        referenceId,
        estimate: {
          tierName: selectedTier.name,
          unitPrice: selectedTier.recommendedPrice,
          totalEstimate,
          deposit50Pct
        }
      });
    } catch (error: any) {
      console.error("Error saving public B2B inquiry:", error);
      return res.status(500).json({
        error: "Unable to record your inquiry right now. Please try again shortly."
      });
    }
  });

  let sharedWorkshopSnapshot: any = null;
  let loadStorefrontAgentContext:
    | (() => Promise<{
        incomingOrders: any[];
        outboundQueue: any[];
        agreedCatalog: any;
      }>)
    | null = null;

  // API Route: Authenticated Agent Interaction proxy with Gemini
  app.post("/api/agent/response", rateLimiter, requireStudioOwner, async (req, res) => {
    try {
      const { role, context, history, state } = req.body;
      if (!role || !context) {
        return res.status(400).json({ error: "Missing required fields: role and context are required." });
      }
      if (state && typeof state === "object") {
        sharedWorkshopSnapshot = state;
      }

      let liveContext: { incomingOrders: any[]; outboundQueue: any[]; agreedCatalog: any } | null = null;
      if (loadStorefrontAgentContext) {
        try {
          liveContext = await loadStorefrontAgentContext();
        } catch {
          liveContext = null;
        }
      }

      const mergedIncoming = new Map<string, any>();
      if (Array.isArray(state?.incomingOrders)) {
        state.incomingOrders.forEach((o: any) => {
          if (o?.id) mergedIncoming.set(o.id, o);
        });
      }
      if (Array.isArray(liveContext?.incomingOrders)) {
        liveContext.incomingOrders.forEach((o: any) => {
          if (o?.id) mergedIncoming.set(o.id, o);
        });
      }

      const mergedOutbound = new Map<string, any>();
      if (Array.isArray(state?.outboundQueue)) {
        state.outboundQueue.forEach((q: any) => {
          if (q?.id) mergedOutbound.set(q.id, q);
        });
      }
      if (Array.isArray(liveContext?.outboundQueue)) {
        liveContext.outboundQueue.forEach((q: any) => {
          if (q?.id) mergedOutbound.set(q.id, q);
        });
      }

      const enrichedState = {
        ...(state || {}),
        incomingOrders: Array.from(mergedIncoming.values()).sort((a, b) =>
          (b.receivedAt || "").localeCompare(a.receivedAt || ""),
        ),
        outboundQueue: Array.from(mergedOutbound.values()).sort((a, b) =>
          (b.createdAt || "").localeCompare(a.createdAt || ""),
        ),
      };

      const response = await getAgentResponseServer(
        role,
        context,
        history || [],
        enrichedState,
        liveContext?.agreedCatalog,
      );
      return res.json(response);
    } catch (error: any) {
      console.error("API error inside /api/agent/response:", error);
      return res.status(500).json({
        error: "External cognitive synchronization failure.",
        ...(process.env.NODE_ENV !== "production" ? { details: error?.message } : {})
      });
    }
  });

  // API Route: 2-Way Inter-App Intelligence Bridge (InterAppCapsule v1.0.0)
  app.use(
    "/api/bridge",
    rateLimiter,
    createBridgeRouter({
      getDb: getFirestoreDb,
      resolveOwnerUid,
      requireStudioOwner,
    }),
  );

  // API Route: LJWellness Storefront <-> StudioOS Connector (ljw-storefront-v1)
  app.use(
    "/api/storefront",
    rateLimiter,
    createStorefrontRouter({
      getDb: getFirestoreDb,
      resolveOwnerUid,
      requireStudioOwner,
      getWorkshopSnapshot: () => sharedWorkshopSnapshot,
      setWorkshopSnapshot: (snap) => {
        sharedWorkshopSnapshot = snap;
      },
      registerAgentContextLoader: (loader) => {
        loadStorefrontAgentContext = loader;
      },
    }),
  );

  // Unknown API endpoints return JSON 404 rather than HTML SPA fallback
  app.use("/api", (_req, res) => {
    res.status(404).json({ error: "API route not found." });
  });

  // Vite middleware for development (dynamically imported so production runtime does not require vite)
  if (process.env.NODE_ENV !== "production") {
    // Prevent the browser from caching development assets (index.html, chunk hashes, etc.)
    app.use((req, res, next) => {
      res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
      res.setHeader("Pragma", "no-cache");
      res.setHeader("Expires", "0");
      res.setHeader("Surrogate-Control", "no-store");
      next();
    });

    const { createServer: createViteServer } = await import("vite");
    const vite = await createViteServer({
      server: { middlewareMode: true },
      appType: "spa",
    });
    app.use(vite.middlewares);
  } else {
    const distPath = resolveDistDir();
    const distIndexPath = path.join(distPath, "index.html");
    const hasDistBuild = fs.existsSync(distIndexPath);
    if (!hasDistBuild) {
      console.error(
        `[StudioOS] Production bundle missing at ${distIndexPath}. Run "npm run build" and ensure root index.html / src/ are not served statically by Apache.`,
      );
    }
    app.use(express.static(distPath));
    app.get("*", (_req, res) => {
      if (!fs.existsSync(distIndexPath)) {
        return res
          .status(503)
          .type("text/plain")
          .send("Artisan 2nd Brain production build (dist/index.html) is missing. Run npm run build and upload dist/ + dist-server/.");
      }
      return res.sendFile(distIndexPath);
    });
  }

  if (typeof PORT === "string") {
    app.listen(PORT, () => {
      console.log(`Artisan 2nd Brain listening on socket ${PORT}`);
    });
  } else {
    app.listen(PORT, "0.0.0.0", () => {
      console.log(`Artisan 2nd Brain running on http://localhost:${PORT}`);
    });
  }
}

startServer();
