/**
 * Marketing Calendar & Timing — AI Prompt Builders
 *
 * Builds system + user prompts for the 3-stage pipeline:
 *   Stage 1 — Seasonal marketing calendar structure & timing recommendations
 *   Stage 2 — Budget allocation suggestions per channel / quarter
 *   Stage 3 — Specific event ideas & content themes
 */

import type { PromptResult } from './introScriptPrompts';

// ─── Inputs ────────────────────────────────────────────────────

export interface MarketingCalendarInputs {
  companyName: string;
  companyDescription?: string;
  industry?: string;
  targetMarket?: string;
  currentChannels?: string[];
  annualBudget?: number;
  season?: string;
  year?: number;
  harmonyText?: string;
  targetCount?: number;
}

// ─── Anti-generic / JSON instructions ──────────────────────────

const BANNED_PHRASES = [
  'leverage', 'synergy', 'holistic', 'robust', 'cutting-edge',
  'innovative', 'seamless', 'next-gen', 'best-in-class', 'game-changing',
  'paradigm shift', 'deep dive', 'low-hanging fruit', 'move the needle',
];

const ANTI_GENERIC_INSTRUCTION = `
CRITICAL: Do NOT use generic marketing jargon or vague phrases. Be specific to this company's
industry, audience, and competitive landscape. Every recommendation must be actionable and concrete.
Banned phrases: ${BANNED_PHRASES.map(p => `"${p}"`).join(', ')}.
Replace generic terms with industry-specific, data-backed language.`;

const JSON_INSTRUCTION = `
Return ONLY valid JSON matching the schema. No markdown fences, no commentary, no trailing commas.
All strings must be properly escaped. Numbers must be numeric, not quoted strings.`;

// ─── Context builder ───────────────────────────────────────────

function buildCompanyContext(inputs: MarketingCalendarInputs): string {
  const parts: string[] = [];
  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Description: ${inputs.companyDescription}`);
  if (inputs.industry) parts.push(`Industry: ${inputs.industry}`);
  if (inputs.targetMarket) parts.push(`Target Market: ${inputs.targetMarket}`);
  if (inputs.currentChannels?.length) parts.push(`Current Channels: ${inputs.currentChannels.join(', ')}`);
  if (inputs.annualBudget) parts.push(`Annual Marketing Budget: $${inputs.annualBudget.toLocaleString()}`);
  if (inputs.season) parts.push(`Focus Season: ${inputs.season}`);
  if (inputs.year) parts.push(`Year: ${inputs.year}`);
  if (inputs.harmonyText) parts.push(`\nBrand & Visual Identity Context:\n${inputs.harmonyText}`);
  return parts.join('\n');
}

// ─── Stage 1: Seasonal Calendar Structure ─────────────────────

export function buildMarketingCalendarSeasonalPrompt(inputs: MarketingCalendarInputs): PromptResult {
  const systemPrompt = `You are an expert marketing strategist specialising in seasonal planning and calendar management.

${ANTI_GENERIC_INSTRUCTION}

Given the company context below, generate a structured seasonal marketing calendar with specific timing recommendations.

${JSON_INSTRUCTION}

SCHEMA:
{
  "seasonalPlan": {
    "name": "string — descriptive name for the seasonal plan",
    "description": "string — 2-3 sentence overview",
    "season": "string — one of: spring, summer, autumn, winter, q1, q2, q3, q4, holiday, custom",
    "year": "number",
    "themes": ["string — up to 5 seasonal themes / content pillars"],
    "targetChannels": ["string — recommended marketing channels for this season"],
    "budgetAllocation": { "channelOrCategory": "number — budget percentage or amount" },
    "keyDates": ["string — important dates for this season (holidays, industry events, etc.)"],
    "goals": ["string — measurable seasonal marketing goals"],
    "status": "draft"
  },
  "timingRecommendations": [
    {
      "timeframe": "string — e.g., 'Early Q1', 'Holiday Season Prep'",
      "eventType": "string — one of: campaign, content, event, product-launch, seasonal, promotion, milestone, other",
      "priority": "string — one of: critical, high, medium, low",
      "description": "string — what to do and why",
      "recommendedStartDate": "string — ISO date or relative date",
      "channels": ["string"],
      "expectedImpact": "string — brief description of expected impact"
    }
  ]
}`;

  const userPrompt = `Generate a seasonal marketing calendar and timing recommendations for:

${buildCompanyContext(inputs)}

Provide a comprehensive seasonal plan with specific timing recommendations, key dates, and strategic priorities.`;

  return { systemPrompt, userPrompt, maxTokens: 6000 };
}

// ─── Stage 2: Budget Allocation ────────────────────────────────

export function buildMarketingCalendarBudgetPrompt(inputs: MarketingCalendarInputs, seasonalResults?: Record<string, any>): PromptResult {
  const systemPrompt = `You are a marketing budget strategist who specialises in optimal budget allocation across channels and time periods.

${ANTI_GENERIC_INSTRUCTION}

Given the company context and seasonal plan, generate a detailed budget allocation strategy.

${JSON_INSTRUCTION}

SCHEMA:
{
  "budgetPlan": {
    "totalBudget": "number",
    "quarterlyBreakdown": [
      {
        "quarter": "string — Q1, Q2, Q3, or Q4",
        "percentage": "number — percentage of total budget",
        "amount": "number — dollar amount",
        "focus": "string — key focus areas for this quarter",
        "priority": "string — one of: critical, high, medium, low"
      }
    ],
    "channelAllocation": [
      {
        "channel": "string — marketing channel name",
        "percentage": "number — percentage of total budget",
        "amount": "number — dollar amount",
        "roiExpectation": "string — expected ROI description",
        "funnelFocus": "string — primary funnel stage"
      }
    ]
  },
  "calendarEvents": [
    {
      "title": "string — event name",
      "eventType": "string — one of: campaign, content, event, product-launch, seasonal, promotion, milestone, other",
      "priority": "string — one of: critical, high, medium, low",
      "status": "string — one of: draft, scheduled, in-progress, completed, cancelled",
      "startDate": "string — ISO date",
      "endDate": "string — ISO date (optional)",
      "budgetAllocated": "number",
      "channels": ["string"],
      "targetAudience": "string",
      "goals": ["string"],
      "quarter": "string — Q1, Q2, Q3, or Q4"
    }
  ]
}`;

  const seasonalContext = seasonalResults ? `\n\nSeasonal Plan Context:\n${JSON.stringify(seasonalResults, null, 2)}` : '';

  const userPrompt = `Generate a detailed budget allocation and calendar events for:

${buildCompanyContext(inputs)}
${seasonalContext}

Create specific calendar events with budget allocations, timing, and channel recommendations.`;

  return { systemPrompt, userPrompt, maxTokens: 8000 };
}

// ─── Stage 3: Event Ideas & Content Themes ─────────────────────

export function buildMarketingCalendarEventsPrompt(inputs: MarketingCalendarInputs, budgetResults?: Record<string, any>): PromptResult {
  const targetCount = inputs.targetCount || 5;

  const systemPrompt = `You are a creative marketing strategist who generates specific, actionable campaign and event ideas.

${ANTI_GENERIC_INSTRUCTION}

Given the company context, seasonal plan, and budget allocation, generate ${targetCount} specific marketing calendar events with detailed content themes.

${JSON_INSTRUCTION}

SCHEMA:
{
  "events": [
    {
      "title": "string — specific, actionable event name",
      "description": "string — 2-3 sentence description with specific tactics",
      "eventType": "string — one of: campaign, content, event, product-launch, seasonal, promotion, milestone, other",
      "priority": "string — one of: critical, high, medium, low",
      "status": "draft",
      "startDate": "string — ISO date",
      "endDate": "string — ISO date",
      "recurrence": "string — one of: none, daily, weekly, biweekly, monthly, quarterly, annually",
      "budgetAllocated": "number — estimated budget in dollars",
      "channels": ["string — specific channels to use"],
      "targetAudience": "string — specific audience segment",
      "goals": ["string — 2-3 measurable goals"],
      "kpis": ["string — 2-3 key performance indicators"],
      "quarter": "string — Q1, Q2, Q3, or Q4",
      "tags": ["string — categorisation tags"]
    }
  ]
}`;

  const budgetContext = budgetResults ? `\n\nBudget Allocation Context:\n${JSON.stringify(budgetResults, null, 2)}` : '';

  const userPrompt = `Generate ${targetCount} specific marketing calendar events for:

${buildCompanyContext(inputs)}
${budgetContext}

Each event should be specific to this company's industry, audience, and brand. Include concrete tactics, measurable goals, and realistic timelines.`;

  return { systemPrompt, userPrompt, maxTokens: 8000 };
}

export type { PromptResult };