/**
 * Website Planner AI Context Routes
 *
 * API endpoints for Website Planner AI generation.
 * POST /auto-fill — generate website planner data from company context
 * POST /regenerate — regenerate website planner data using existing context
 */

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';
import { authenticate } from '../middleware/auth';
import { requirePermission } from '../middleware/permissions';
import { WebsitePlannerPipeline } from '../services/aiContext/websitePlannerPipeline';
import { WebsitePlannerPipelineInputs } from '../services/aiContext/websitePlannerPrompts';
import { aiContextService, computeWebsitePlannerAutoFillMapping } from '../services/aiContext/aiContextService';
import { getModels } from '../models';
import { createJob, updateJobProgress, completeJob, failJob, getJob } from '../services/aiContext/aiJobManager';

const router = express.Router();
router.use(authenticate);

router.get(
  '/status/:jobId',
  async (req: Request, res: Response) => {
    const { jobId } = req.params;
    const job = getJob(jobId);

    if (!job) {
      res.status(404).json({ error: 'Job not found' });
      return;
    }

    res.json({
      jobId: job.jobId,
      status: job.status,
      progress: job.progress,
      step: job.step,
      result: job.result,
      error: job.error,
    });
  }
);

// ============================================
// POST /auto-fill
// ============================================

router.post(
  '/auto-fill',
  requirePermission('website-planner', 'ai-generate'),
  [
    body('companyId').notEmpty().withMessage('Company ID is required'),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({ error: 'Validation failed', details: errors.array() });
      return;
    }

    const { companyId, targetPlatform, language, customInstructions, templateStyleId, templateStyleName } = req.body;

    try {
      // Start async generation
      const job = createJob('website-planner', companyId, req.body._moduleId);

      // Log language for debugging
      console.log(`[WebsitePlanner-AutoFill] Job ${job.jobId} language: ${language || 'English (default)'}`);
      if (customInstructions) console.log(`[WebsitePlanner-AutoFill] Job ${job.jobId} customInstructions: "${customInstructions.substring(0, 100)}${customInstructions.length > 100 ? '...' : ''}"`);

      // Return jobId immediately so the frontend can poll
      res.status(202).json({ jobId: job.jobId, status: 'processing' });

      // Run pipeline in background (do NOT await on the response path)
      setImmediate(async () => {
        try {
          // Generate from company data
          const { Company, BusinessProfile, ICP } = getModels();
          const company = await Company.findById(companyId);
          if (!company) {
            failJob(job.jobId, 'Company not found');
            return;
          }

          let businessProfile: any = null;
          try { businessProfile = await BusinessProfile.findOne({ companyId }); } catch {}

          const companyContexts = await aiContextService.getByCompany(companyId, 'company-creation');
          const latestCompanyContext = companyContexts.find((c: any) => {
            const a = c.analysis?.toObject?.() || c.analysis || {};
            return c.status === 'approved' || a.industryType || a.businessModel || a.businessSummary;
          });

          let icpData: any = null;
          try { icpData = await ICP.findOne({ companyId, isActive: true }).sort({ createdAt: -1 }); } catch {}

          // Load brand strategy context for enrichment
          let brandStrategyData: any = null;
          try {
            const { ModuleData } = getModels();
            const brandStrategyDoc = await ModuleData.findOne({ moduleId: 'brand-strategy', companyId });
            if (brandStrategyDoc?.data) {
              brandStrategyData = brandStrategyDoc.data;
            }
          } catch {}

          // Build pipeline inputs
          const pipelineInputs: WebsitePlannerPipelineInputs = {
            companyName: company.name,
            companyDescription: company.description || businessProfile?.description || undefined,
            companyIndustry: businessProfile?.primaryIndustry || undefined,
            companyBusinessModel: businessProfile?.businessModel || undefined,
            companyTargetAudience: undefined,
            companyPrimaryOffering: undefined,
            companyUsps: undefined,
            targetPlatform: targetPlatform || undefined,
            // Language for content generation (ISO code or full name, e.g. 'hi', 'mr', 'Hindi')
            language: language || undefined,
            // User-provided custom instructions / prompt
            customInstructions: customInstructions || undefined,
            // Template style context
            templateStyleId: templateStyleId || undefined,
            templateStyleName: templateStyleName || undefined,
          };

          if (latestCompanyContext) {
            const analysis = (latestCompanyContext as any).analysis?.toObject?.() || (latestCompanyContext as any).analysis || {};
            if (analysis.industryType && !pipelineInputs.companyIndustry) pipelineInputs.companyIndustry = analysis.industryType;
            if (analysis.businessModel && !pipelineInputs.companyBusinessModel) pipelineInputs.companyBusinessModel = analysis.businessModel;
            if (analysis.targetAudience?.primary) pipelineInputs.companyTargetAudience = analysis.targetAudience.primary;
            if (analysis.primaryOffering) pipelineInputs.companyPrimaryOffering = analysis.primaryOffering;
            if (analysis.uspSuggestions?.length) pipelineInputs.companyUsps = analysis.uspSuggestions;
          }

          if (icpData) {
            pipelineInputs.icpName = icpData.name || undefined;
            pipelineInputs.icpIndustry = icpData.industry || undefined;
            pipelineInputs.icpCompanySize = icpData.companySize || undefined;
            pipelineInputs.icpPainPoints = icpData.painPoints || undefined;
            pipelineInputs.icpBusinessGoals = icpData.businessGoals || undefined;
          }

          if (brandStrategyData) {
            pipelineInputs.brandArchetype = brandStrategyData.brandArchetype || undefined;
            pipelineInputs.brandPersonality = brandStrategyData.brandPersonality || undefined;
            pipelineInputs.brandValues = brandStrategyData.brandValues || undefined;
            pipelineInputs.brandPositioning = brandStrategyData.brandPositioning || undefined;
            pipelineInputs.brandVoice = brandStrategyData.brandVoice || undefined;
            pipelineInputs.primaryColor = brandStrategyData.primaryColor || undefined;
          }

          updateJobProgress(job.jobId, 10, 'Preparing business context...');
          const pipeline = new WebsitePlannerPipeline(pipelineInputs, (progress, step) => {
            updateJobProgress(job.jobId, progress, step);
          });
          const result = await pipeline.run();

          const context = await aiContextService.create({
            companyId,
            moduleSource: 'website-planner',
            analysisType: 'full-analysis',
            inputs: { companyName: company.name, description: pipelineInputs.companyDescription },
            analysis: result.analysis,
            metadata: {
              pipelineVersion: result.pipelineVersion,
              provider: result.provider,
              model: result.aiModel,
              tokensUsed: result.tokensUsed,
              inputTokens: result.inputTokens,
              outputTokens: result.outputTokens,
              processingTimeMs: result.processingTimeMs,
              latencyMs: result.latencyMs,
              overallConfidence: result.overallConfidence,
              fieldConfidences: result.fieldConfidences,
              finishReason: result.finishReason,
              apiKeyMasked: result.apiKeyMasked,
            },
          });

          await aiContextService.updateStatus(context.id, 'approved');

          const autoFillData = computeWebsitePlannerAutoFillMapping(result.analysis);
          completeJob(job.jobId, autoFillData, 'generated');

          console.log(`[WebsitePlanner-AutoFill] Job ${job.jobId} completed. Source: generated`);
        } catch (err: any) {
          console.error(`[WebsitePlanner-AutoFill] Job ${job.jobId} failed:`, err.message);
          failJob(job.jobId, err.message || 'AI generation failed');
        }
      });
    } catch (error: any) {
      console.error('[WebsitePlanner-AutoFill] Error:', error.message);
      res.status(500).json({ error: 'Failed to generate website planner data', details: error.message });
    }
  }
);

// ============================================
// POST /regenerate
// ============================================

router.post(
  '/regenerate',
  requirePermission('website-planner', 'ai-generate'),
  [
    body('companyId').notEmpty().withMessage('Company ID is required'),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(400).json({ error: 'Validation failed', details: errors.array() });
      return;
    }

    const { companyId, existingPlannerData, targetPlatform, language, customInstructions } = req.body;

    // Create job and return immediately
    const job = createJob('website-planner', companyId, req.body._moduleId);
    res.status(202).json({ jobId: job.jobId, status: 'processing' });

    // Run pipeline in background
    setImmediate(async () => {
      try {
        const { Company, BusinessProfile, ICP } = getModels();
        const company = await Company.findById(companyId);
        if (!company) {
          failJob(job.jobId, 'Company not found');
          return;
        }

        let businessProfile: any = null;
        try { businessProfile = await BusinessProfile.findOne({ companyId }); } catch {}

        const companyContexts = await aiContextService.getByCompany(companyId, 'company-creation');
        const latestCompanyContext = companyContexts.find((c: any) => {
          const a = c.analysis?.toObject?.() || c.analysis || {};
          return c.status === 'approved' || a.industryType || a.businessModel || a.businessSummary;
        });

        let icpData: any = null;
        try { icpData = await ICP.findOne({ companyId, isActive: true }).sort({ createdAt: -1 }); } catch {}

        // Load brand strategy context for enrichment
        let brandStrategyData: any = null;
        try {
          const { ModuleData } = getModels();
          const brandStrategyDoc = await ModuleData.findOne({ moduleId: 'brand-strategy', companyId });
          if (brandStrategyDoc?.data) {
            brandStrategyData = brandStrategyDoc.data;
          }
        } catch {}

        // Build pipeline inputs with existing planner data for regeneration
        const pipelineInputs: WebsitePlannerPipelineInputs = {
          companyName: company.name,
          companyDescription: company.description || businessProfile?.description || undefined,
          companyIndustry: businessProfile?.primaryIndustry || undefined,
          companyBusinessModel: businessProfile?.businessModel || undefined,
          companyTargetAudience: undefined,
          companyPrimaryOffering: undefined,
          companyUsps: undefined,
          // Target platform for generation
          targetPlatform: targetPlatform || undefined,
          // Language for content generation
          language: language || undefined,
          // User-provided custom instructions / prompt
          customInstructions: customInstructions || undefined,
          // Existing planner identity for regeneration
          existingPlannerName: existingPlannerData?.name || undefined,
          existingPlannerType: existingPlannerData?.websiteType || undefined,
          existingPlannerDomain: existingPlannerData?.domain || undefined,
          existingPlannerGoal: existingPlannerData?.websiteGoal || undefined,
        };

        if (latestCompanyContext) {
          const analysis = (latestCompanyContext as any).analysis?.toObject?.() || (latestCompanyContext as any).analysis || {};
          if (analysis.industryType && !pipelineInputs.companyIndustry) pipelineInputs.companyIndustry = analysis.industryType;
          if (analysis.businessModel && !pipelineInputs.companyBusinessModel) pipelineInputs.companyBusinessModel = analysis.businessModel;
          if (analysis.targetAudience?.primary) pipelineInputs.companyTargetAudience = analysis.targetAudience.primary;
          if (analysis.primaryOffering) pipelineInputs.companyPrimaryOffering = analysis.primaryOffering;
          if (analysis.uspSuggestions?.length) pipelineInputs.companyUsps = analysis.uspSuggestions;
        }

        if (icpData) {
          pipelineInputs.icpName = icpData.name || undefined;
          pipelineInputs.icpIndustry = icpData.industry || undefined;
          pipelineInputs.icpCompanySize = icpData.companySize || undefined;
          pipelineInputs.icpPainPoints = icpData.painPoints || undefined;
          pipelineInputs.icpBusinessGoals = icpData.businessGoals || undefined;
        }

        if (brandStrategyData) {
          pipelineInputs.brandArchetype = brandStrategyData.brandArchetype || undefined;
          pipelineInputs.brandPersonality = brandStrategyData.brandPersonality || undefined;
          pipelineInputs.brandValues = brandStrategyData.brandValues || undefined;
          pipelineInputs.brandPositioning = brandStrategyData.brandPositioning || undefined;
          pipelineInputs.brandVoice = brandStrategyData.brandVoice || undefined;
          pipelineInputs.primaryColor = brandStrategyData.primaryColor || undefined;
        }

        updateJobProgress(job.jobId, 10, 'Preparing business context...');
        const pipeline = new WebsitePlannerPipeline(pipelineInputs, (progress, step) => {
          updateJobProgress(job.jobId, progress, step);
        });
        const result = await pipeline.run();

        const context = await aiContextService.create({
          companyId,
          moduleSource: 'website-planner',
          analysisType: 'full-analysis',
          inputs: { companyName: company.name, description: pipelineInputs.companyDescription },
          analysis: result.analysis,
          metadata: {
            pipelineVersion: result.pipelineVersion,
            provider: result.provider,
            model: result.aiModel,
            tokensUsed: result.tokensUsed,
            inputTokens: result.inputTokens,
            outputTokens: result.outputTokens,
            processingTimeMs: result.processingTimeMs,
            latencyMs: result.latencyMs,
            overallConfidence: result.overallConfidence,
            fieldConfidences: result.fieldConfidences,
            finishReason: result.finishReason,
            apiKeyMasked: result.apiKeyMasked,
          },
        });

        await aiContextService.updateStatus(context.id, 'approved');

        const autoFillData = computeWebsitePlannerAutoFillMapping(result.analysis);
        completeJob(job.jobId, autoFillData, 'regenerated');
        console.log(`[WebsitePlanner-Regenerate] Job ${job.jobId} completed. Source: regenerated`);
      } catch (err: any) {
        console.error(`[WebsitePlanner-Regenerate] Job ${job.jobId} failed:`, err.message);
        failJob(job.jobId, err.message || 'AI regeneration failed');
      }
    });
  }
);

export default router;