import { GoogleGenAI, Type, FunctionDeclaration } from "@google/genai";
import type { AgentRole, IncomingOrderQuote, Message } from "../types.js";
import {
  auditStudioInventory,
  buildSkuBomCatalog,
  evaluateCollectionAndFormulationCogs,
  evaluateIncomingOrderOrQuote,
  STUDIO_PRICING_RULES,
} from "../lib/studioOperations.js";
import { buildDefaultAgreementCatalog, type StorefrontAgreementCatalog } from "../lib/storefrontBridge.js";

// Initialize Gemini on the server side with the telemetry User-Agent header
const ai = new GoogleGenAI({
  apiKey: process.env.GEMINI_API_KEY || "",
  httpOptions: {
    headers: {
      'User-Agent': 'aistudio-build',
    }
  }
});

const create_task: FunctionDeclaration = {
  name: "create_task",
  description: "Create a new production task or directive in the workshop.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      title: { type: Type.STRING, description: "Short title of the task" },
      description: { type: Type.STRING, description: "Detailed description of what needs to be done" },
      assignedTo: { type: Type.STRING, enum: ['StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'], description: "The specialist to handle this task" },
      priority: { type: Type.STRING, enum: ['low', 'medium', 'high'], description: "Task priority" }
    },
    required: ["title", "description", "assignedTo", "priority"]
  }
};

const complete_task: FunctionDeclaration = {
  name: "complete_task",
  description: "Mark a pending task or directive as completed in the workshop database after performing the work or generating the required output.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      taskId: { type: Type.STRING, description: "The ID of the task to complete (e.g., 't1', 't2') or task title" },
      completionNotes: { type: Type.STRING, description: "Summary of the completed work, formulations, or decisions" },
      actualOutcome: { type: Type.STRING, description: "The tangible result produced (e.g. 'Formulation created and logged', 'Inventory restocked')" }
    },
    required: ["taskId"]
  }
};

const batch_complete_tasks: FunctionDeclaration = {
  name: "batch_complete_tasks",
  description: "Mark multiple or all pending tasks as completed when executing bulk directives or clearing the backlog.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      taskIds: { 
        type: Type.ARRAY, 
        items: { type: Type.STRING },
        description: "List of task IDs to complete (or leave empty if completing by role)" 
      },
      assignedTo: { 
        type: Type.STRING, 
        enum: ['all', 'StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'],
        description: "Complete all pending tasks assigned to this specialist role, or 'all'" 
      },
      summaryNotes: { type: Type.STRING, description: "Overall summary of work executed for these directives" }
    },
    required: ["summaryNotes"]
  }
};

const update_task_status: FunctionDeclaration = {
  name: "update_task_status",
  description: "Update the status of a specific task.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      taskId: { type: Type.STRING, description: "The ID of the task" },
      status: { type: Type.STRING, enum: ['pending', 'in-progress', 'completed'], description: "The new task status" },
      notes: { type: Type.STRING, description: "Progress notes" }
    },
    required: ["taskId", "status"]
  }
};

const update_inventory: FunctionDeclaration = {
  name: "update_inventory",
  description: "Update the stock levels of raw materials or supplies in the workshop.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      item: { type: Type.STRING, description: "Name of the material (e.g., Shea Butter, Lavender Oil)" },
      amount: { type: Type.NUMBER, description: "The amount to add or remove" },
      action: { type: Type.STRING, enum: ['add', 'remove'], description: "Whether to add to or remove from stock" }
    },
    required: ["item", "amount", "action"]
  }
};

const create_asset: FunctionDeclaration = {
  name: "create_asset",
  description: "Save a marketing campaign, strategy report, or branding guide. DO NOT use this for production recipes or formulations - use 'create_formulation' instead.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      title: { type: Type.STRING, description: "Title of the asset" },
      content: { type: Type.STRING, description: "The full content of the recipe, campaign, or report" },
      type: { type: Type.STRING, enum: ['recipe', 'marketing', 'strategy', 'legal', 'finance'], description: "The category of the asset" }
    },
    required: ["title", "content", "type"]
  }
};

const update_finance: FunctionDeclaration = {
  name: "update_finance",
  description: "Record a financial transaction (income or expense) for the studio.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      amount: { type: Type.NUMBER, description: "The dollar amount" },
      description: { type: Type.STRING, description: "What the transaction was for" },
      type: { type: Type.STRING, enum: ['in', 'out'], description: "Whether it's income (in) or an expense (out)" }
    },
    required: ["amount", "description", "type"]
  }
};

const create_project: FunctionDeclaration = {
  name: "create_project",
  description: "Initiate a new artisan series, collection, or product line.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      name: { type: Type.STRING, description: "Name of the project/series" },
      stage: { type: Type.STRING, enum: ['Design', 'Formulation', 'Production', 'Marketing'], description: "Initial stage" },
      health: { type: Type.STRING, enum: ['good', 'warning', 'danger'], description: "Initial health status" }
    },
    required: ["name", "stage", "health"]
  }
};

const create_wholesale_client: FunctionDeclaration = {
  name: "create_wholesale_client",
  description: "Register a new B2B, wholesale, or white-label client.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      name: { type: Type.STRING, description: "Business or client name" },
      type: { type: Type.STRING, enum: ['wholesale', 'white-label'], description: "Partnership type" },
      contact: { type: Type.STRING, description: "Contact email or phone" },
      status: { type: Type.STRING, enum: ['active', 'lead', 'inactive'], description: "Initial status" }
    },
    required: ["name", "type", "contact", "status"]
  }
};

const create_wholesale_order: FunctionDeclaration = {
  name: "create_wholesale_order",
  description: "Process a new B2B or wholesale order for a client.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      clientId: { type: Type.STRING, description: "The ID of the client (if known) or name" },
      items: {
        type: Type.ARRAY,
        items: {
          type: Type.OBJECT,
          properties: {
            item: { type: Type.STRING, description: "Product name" },
            quantity: { type: Type.NUMBER, description: "Quantity ordered" },
            price: { type: Type.NUMBER, description: "Unit price" }
          },
          required: ["item", "quantity", "price"]
        }
      },
      status: { type: Type.STRING, enum: ['pending', 'processing', 'shipped', 'delivered'], description: "Order status" }
    },
    required: ["clientId", "items", "status"]
  }
};

const create_prospect: FunctionDeclaration = {
  name: "create_prospect",
  description: "Add a new potential client or business lead to the CRM.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      name: { type: Type.STRING, description: "Contact name" },
      company: { type: Type.STRING, description: "Company name (optional)" },
      source: { type: Type.STRING, description: "Where the lead came from (e.g., Instagram, Referral)" },
      potentialValue: { type: Type.NUMBER, description: "Estimated potential annual value" },
      notes: { type: Type.STRING, description: "Initial notes or context" }
    },
    required: ["name", "source", "potentialValue"]
  }
};

const add_event: FunctionDeclaration = {
  name: "add_event",
  description: "Add a holiday, sale, market, or production deadline to the Studio Planner.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      title: { type: Type.STRING, description: "Event name" },
      date: { type: Type.STRING, description: "Date in YYYY-MM-DD format" },
      type: { 
        type: Type.STRING, 
        enum: ["production", "marketing", "meeting", "holiday", "sale", "market", "workshop", "popup", "wholesale-deadline"],
        description: "Type of event" 
      },
      category: {
        type: Type.STRING,
        enum: ["Soap", "Candles", "Decor", "General"],
        description: "Focus category"
      },
      description: { type: Type.STRING, description: "Details about the event" }
    },
    required: ["title", "date", "type"]
  }
};

const delegate_to_agent: FunctionDeclaration = {
  name: "delegate_to_agent",
  description: "Hand off the current task or specific inquiry to another specialist agent for deep analysis. Vital for collaborative studio operations.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      targetRole: { 
        type: Type.STRING, 
        enum: ["StudioLead", "Formulator", "Business", "Marketing", "NicheExpert", "WealthAdvisor", "Mentor"],
        description: "The role of the specialist to consult" 
      },
      reason: { type: Type.STRING, description: "Why you are delegating (context for the next agent)" }
    },
    required: ["targetRole", "reason"]
  }
};

const log_outreach: FunctionDeclaration = {
  name: "log_outreach",
  description: "Record a contact attempt or meeting with a prospect.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      prospectId: { type: Type.STRING, description: "The ID of the prospect" },
      method: { type: Type.STRING, enum: ['email', 'call', 'social', 'meeting'], description: "Contact method" },
      notes: { type: Type.STRING, description: "What was discussed" },
      outcome: { type: Type.STRING, description: "The result of the outreach" }
    },
    required: ["prospectId", "method", "notes", "outcome"]
  }
};

const update_prospect_status: FunctionDeclaration = {
  name: "update_prospect_status",
  description: "Move a prospect through the sales funnel.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      prospectId: { type: Type.STRING, description: "The ID of the prospect" },
      status: { type: Type.STRING, enum: ['cold', 'warm', 'hot', 'converted', 'lost'], description: "New status" }
    },
    required: ["prospectId", "status"]
  }
};

const create_campaign: FunctionDeclaration = {
  name: "create_campaign",
  description: "Launch a new marketing campaign on a specific platform.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      name: { type: Type.STRING, description: "Name of the campaign" },
      platform: { type: Type.STRING, enum: ['Instagram', 'TikTok', 'Email', 'Facebook', 'Pinterest', 'Other'], description: "Target platform" },
      budget: { type: Type.NUMBER, description: "Total budget for the campaign" },
      notes: { type: Type.STRING, description: "Campaign goals or strategy" },
      content: { type: Type.STRING, description: "Draft content or copy for the campaign" }
    },
    required: ["name", "platform", "budget"]
  }
};

const update_campaign_budget: FunctionDeclaration = {
  name: "update_campaign_budget",
  description: "Adjust the budget for an existing campaign. This will reflect as a cash outflow.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      campaignId: { type: Type.STRING, description: "The ID of the campaign to update" },
      newBudget: { type: Type.NUMBER, description: "The new total budget amount" }
    },
    required: ["campaignId", "newBudget"]
  }
};

const analyze_market_trends: FunctionDeclaration = {
  name: "analyze_market_trends",
  description: "Analyze current market trends for a specific niche or product type.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      niche: { type: Type.STRING, description: "The niche to analyze (e.g., 'luxury candles', 'botanical skincare')" },
      focus: { type: Type.STRING, description: "Specific focus (e.g., 'packaging', 'ingredients', 'pricing')" }
    },
    required: ["niche"]
  }
};

const optimize_formula: FunctionDeclaration = {
  name: "optimize_formula",
  description: "Suggest optimizations for a recipe or formula based on cost or safety.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      recipeId: { type: Type.STRING, description: "The ID of the recipe to optimize" },
      goal: { type: Type.STRING, enum: ['cost', 'safety', 'performance'], description: "The optimization goal" }
    },
    required: ["recipeId", "goal"]
  }
};

const create_batch: FunctionDeclaration = {
  name: "create_batch",
  description: "Record a new production batch for a specific recipe/collection.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      collectionId: { type: Type.STRING, description: "The ID of the collection/product line" },
      recipeId: { type: Type.STRING, description: "The ID of the recipe or name of the formulation used" },
      batchNumber: { type: Type.STRING, description: "Unique batch identifier (e.g., LOT-2026-001)" },
      quantity: { type: Type.NUMBER, description: "Total units produced" },
      notes: { type: Type.STRING, description: "Production notes (e.g., temperature, humidity, deviations)" }
    },
    required: ["collectionId", "batchNumber", "quantity"]
  }
};

const create_smart_note: FunctionDeclaration = {
  name: "create_smart_note",
  description: "Create a structured SMART Notebook entry (Specific, Measurable, Achievable, Relevant, Time-Bound) for strategic planning, mindset breakthroughs, fears, 14-year milestone analysis, product vision, or launch readiness. Can automatically spawn studio directives.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      title: { type: Type.STRING, description: "Descriptive title of the SMART note or breakthrough" },
      category: { 
        type: Type.STRING, 
        enum: ['Mindset & Fear', 'Product Strategy', 'Launch Readiness', 'Financial Breakthrough', 'Creative Vision', 'Operational Alignment', 'General'],
        description: "Strategic focus category"
      },
      specific: { type: Type.STRING, description: "Specific: The precise thought, blocker, fear, recurring pattern, or concept being articulated" },
      measurable: { type: Type.STRING, description: "Measurable: The tangible metric, concrete verification test, or quantifiable standard of success" },
      achievable: { type: Type.STRING, description: "Achievable: The realistic action path, specialist delegations, or method to dismantle the blocker" },
      relevant: { type: Type.STRING, description: "Relevant: Why this is vital to the artisan's 14-year journey, legacy, brand prestige, and enterprise growth" },
      timeBound: { type: Type.STRING, description: "Time-Bound: Target milestone or completion date in 2026 (e.g., 'Q3 2026', 'September 2026')" },
      insights: { type: Type.STRING, description: "Deep psychological or strategic coach reflection" },
      actionPlan: { 
        type: Type.ARRAY, 
        items: { type: Type.STRING },
        description: "List of concrete step-by-step action items"
      },
      tags: {
        type: Type.ARRAY,
        items: { type: Type.STRING },
        description: "Categorical tags for filtering (e.g. ['Breakthrough', 'Launch', '14-Year-Milestone'])"
      },
      createDirectives: {
        type: Type.BOOLEAN,
        description: "If true, automatically converts the action steps into pending studio tasks/directives assigned to relevant specialists"
      }
    },
    required: ["title", "category", "specific", "measurable", "achievable", "relevant", "timeBound"]
  }
};

const update_smart_note: FunctionDeclaration = {
  name: "update_smart_note",
  description: "Update an existing SMART Note in the notebook (e.g. update status, refine action plan, add insights, or adjust 2026 timeline).",
  parameters: {
    type: Type.OBJECT,
    properties: {
      id: { type: Type.STRING, description: "The ID or title of the note to update" },
      title: { type: Type.STRING, description: "Updated title" },
      status: { 
        type: Type.STRING, 
        enum: ['draft', 'in-review', 'actionable', 'converted-to-directives', 'archived'],
        description: "Lifecycle status"
      },
      category: { type: Type.STRING, description: "Updated category" },
      specific: { type: Type.STRING, description: "Updated Specific description" },
      measurable: { type: Type.STRING, description: "Updated Measurable description" },
      achievable: { type: Type.STRING, description: "Updated Achievable description" },
      relevant: { type: Type.STRING, description: "Updated Relevant description" },
      timeBound: { type: Type.STRING, description: "Updated Time-Bound target in 2026" },
      insights: { type: Type.STRING, description: "Additional strategic coach reflections" },
      actionPlan: { 
        type: Type.ARRAY, 
        items: { type: Type.STRING },
        description: "Updated action items" 
      },
      tags: { 
        type: Type.ARRAY, 
        items: { type: Type.STRING },
        description: "Updated tags" 
      }
    },
    required: ["id"]
  }
};

const delete_smart_note: FunctionDeclaration = {
  name: "delete_smart_note",
  description: "Permanently delete a note from the SMART Notebook.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      id: { type: Type.STRING, description: "The ID of the SMART note to remove" }
    },
    required: ["id"]
  }
};

const convert_note_to_directives: FunctionDeclaration = {
  name: "convert_note_to_directives",
  description: "Transform the action items of a SMART Note into official studio directives assigned to specialist agents.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      noteId: { type: Type.STRING, description: "The ID of the SMART note" },
      assignedRole: { 
        type: Type.STRING, 
        enum: ['StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'],
        description: "Default specialist to assign the generated directives to"
      }
    },
    required: ["noteId"]
  }
};

const create_formulation: FunctionDeclaration = {
  name: "create_formulation",
  description: "Create a precision product formulation with specific ingredients and measurements. Use this for actual production recipes.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      name: { type: Type.STRING, description: "Name of the formulation" },
      ingredients: { 
        type: Type.ARRAY, 
        items: {
          type: Type.OBJECT,
          properties: {
            name: { type: Type.STRING, description: "Ingredient name (must ideally match an inventory item)" },
            amount: { type: Type.NUMBER, description: "Measurement amount" },
            unit: { type: Type.STRING, description: "Measurement unit (e.g., g, ml, drops)" }
          },
          required: ["name", "amount", "unit"]
        }
      },
      instructions: { type: Type.STRING, description: "Step-by-step crafting instructions" },
      curingTimeDays: { type: Type.NUMBER, description: "Required curing or infusion time in days" },
      batchSize: { type: Type.NUMBER, description: "Total expected yield quantity" },
      batchUnit: { type: Type.STRING, description: "Yield unit (e.g., bars, bottles, g)" }
    },
    required: ["name", "ingredients", "instructions", "curingTimeDays", "batchSize", "batchUnit"]
  }
};

const migrate_recipe_asset: FunctionDeclaration = {
  name: "migrate_recipe_asset",
  description: "Move a misfiled recipe from 'Creative Notes' (assets) to 'Precision Formulas' (formulations).",
  parameters: {
    type: Type.OBJECT,
    properties: {
      assetId: { type: Type.STRING, description: "The ID of the asset to migrate" },
      ingredients: { 
        type: Type.ARRAY, 
        items: {
          type: Type.OBJECT,
          properties: {
            name: { type: Type.STRING, description: "Ingredient name" },
            amount: { type: Type.NUMBER, description: "Amount" },
            unit: { type: Type.STRING, description: "Unit" }
          },
          required: ["name", "amount", "unit"]
        }
      }
    },
    required: ["assetId", "ingredients"]
  }
};

const calculate_saponification: FunctionDeclaration = {
  name: "calculate_saponification",
  description: "Calculate precise saponification values, NaOH/KOH lye requirement, water discount, and fatty acid profile (Hardness, Cleansing, Conditioning, Bubbly, Creamy, INS score) for any custom oil blend.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      soapName: { type: Type.STRING, description: "Name of the soap recipe" },
      oils: {
        type: Type.ARRAY,
        items: {
          type: Type.OBJECT,
          properties: {
            name: { type: Type.STRING, description: "Oil/Fat name (e.g., Olive Oil, Coconut Oil 76 deg, Shea Butter, Castor Oil)" },
            grams: { type: Type.NUMBER, description: "Weight in grams" }
          },
          required: ["name", "grams"]
        },
        description: "List of oils and their weights in grams"
      },
      superfatPercent: { type: Type.NUMBER, description: "Superfat/lye discount percentage (typically 5 to 8)" },
      waterLyeRatio: { type: Type.NUMBER, description: "Water to lye ratio (e.g. 2.0 or 2.5)" },
      lyeType: { type: Type.STRING, enum: ['NaOH', 'KOH', 'Dual_90_10'], description: "Lye type (NaOH for solid bars, KOH for liquid soap)" }
    },
    required: ["soapName", "oils", "superfatPercent", "waterLyeRatio", "lyeType"]
  }
};

const audit_formulation_safety: FunctionDeclaration = {
  name: "audit_formulation_safety",
  description: "Audit formulation for IFRA dermal compliance limits, antioxidant protection against rancidity (e.g., Tocopherol/ROCO2), pH range, and microbial preservation.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      productName: { type: Type.STRING, description: "Name of the product formulation" },
      productType: { 
        type: Type.STRING, 
        enum: ['leave_on_serum', 'leave_on_butter', 'rinse_off_soap', 'emulsified_lotion', 'bath_soak'], 
        description: "Category of cosmetic product" 
      },
      preservativeSystem: { type: Type.STRING, description: "Preservative or self-preserving anhydrous matrix" },
      fragrancePercent: { type: Type.NUMBER, description: "Total essential oil or fragrance concentration percentage" },
      shelfLifeEstimateMonths: { type: Type.NUMBER, description: "Estimated shelf stability in months" }
    },
    required: ["productName", "productType", "preservativeSystem", "fragrancePercent", "shelfLifeEstimateMonths"]
  }
};

const scale_formulation: FunctionDeclaration = {
  name: "scale_formulation",
  description: "Scale a formulation's batch size proportionally while preserving precise ingredient percentages, lye ratios, and phase distributions.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      formulationName: { type: Type.STRING, description: "Name or ID of the formulation to scale" },
      currentBatchSize: { type: Type.NUMBER, description: "Current batch size" },
      targetBatchSize: { type: Type.NUMBER, description: "Target batch size" },
      unit: { type: Type.STRING, description: "Unit of measurement (e.g., g, kg, bars, bottles)" }
    },
    required: ["formulationName", "currentBatchSize", "targetBatchSize", "unit"]
  }
};

const delete_record: FunctionDeclaration = {
  name: "delete_record",
  description: "Permanently remove a record from the hub (task, prospect, campaign, formulation, asset, inventory, order, collection, etc.). Use with extreme caution.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      recordType: { 
        type: Type.STRING, 
        enum: ["task", "prospect", "campaign", "formulation", "asset", "inventory", "order", "collection"], 
        description: "The type of record to delete" 
      },
      id: { type: Type.STRING, description: "The ID of the record to remove" }
    },
    required: ["recordType", "id"]
  }
};

const create_corporate_account: FunctionDeclaration = {
  name: "create_corporate_account",
  description: "Register a new B2B commercial account (Luxury Builder, Condo Developer, Rental Developer, Realtor, or Brokerage) in the Builders & Realtors CRM.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      companyName: { type: Type.STRING, description: "Company or brokerage name" },
      contactPerson: { type: Type.STRING, description: "Primary decision-maker name" },
      email: { type: Type.STRING, description: "Business email address" },
      phone: { type: Type.STRING, description: "Business phone number (optional)" },
      accountType: {
        type: Type.STRING,
        enum: ["Luxury Builder", "Condo Developer", "Rental Developer", "Realtor", "Architecture / Design", "Corporate Gifting", "Luxury Hospitality", "Boutique Retail"],
        description: "Target B2B vertical"
      },
      nicheFocus: { type: Type.STRING, description: "Project niche or gifting scope (optional)" },
      annualBudgetPotential: { type: Type.NUMBER, description: "Estimated annual B2B contract value in CAD/USD (optional)" },
      notes: { type: Type.STRING, description: "Account notes or handover timeline (optional)" }
    },
    required: ["companyName", "contactPerson", "email", "accountType"]
  }
};

const create_development_portal: FunctionDeclaration = {
  name: "create_development_portal",
  description: "Create a public QR development handover portal and A3 binder specification for a condo development, rental tower, or custom home builder project.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      developmentName: { type: Type.STRING, description: "Name of the residential building or estate project" },
      developerName: { type: Type.STRING, description: "Name of the builder or developer company" },
      addressOrLocation: { type: Type.STRING, description: "City, neighborhood, or street address" },
      unitCount: { type: Type.NUMBER, description: "Total units/lots in the project (optional)" },
      boxEdition: {
        type: Type.STRING,
        enum: ["Uniform Development QR", "Custom Single-Buyer", "Builder Wholesale Run"],
        description: "Kit packaging and binder format"
      },
      audienceMode: {
        type: Type.STRING,
        enum: ["homeowner", "renter"],
        description: "Use 'homeowner' for condo buyers/estates or 'renter' for luxury rental tower tenants"
      },
      scentProfile: { type: Type.STRING, description: "Botanical scent profile paired with the project (optional)" },
      published: { type: Type.BOOLEAN, description: "Whether to publish immediately for QR scans (optional)" }
    },
    required: ["developmentName", "developerName", "addressOrLocation"]
  }
};

const generate_french_compliance_pack: FunctionDeclaration = {
  name: "generate_french_compliance_pack",
  description: "Generate a complete Quebec Loi 96 / OQLF & Health Canada bilingual label pack, French care card, and B2B French commercial quote clause, and save it in Documents Hub.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      productType: {
        type: Type.STRING,
        enum: ["soap", "candle", "serum", "box"],
        description: "Product category for statutory bilingual warnings"
      },
      productNameFr: { type: Type.STRING, description: "French product title" },
      productNameEn: { type: Type.STRING, description: "English product title" },
      netWeight: { type: Type.STRING, description: "Metric net weight/volume (e.g., '120 g', '220 g / 7.7 oz')" },
      scentNotesFr: { type: Type.STRING, description: "French botanical scent notes" },
      scentNotesEn: { type: Type.STRING, description: "English botanical scent notes" },
      inciList: { type: Type.STRING, description: "Descending INCI ingredient declaration" },
      companyAndAddress: { type: Type.STRING, description: "Canadian manufacturer/dealer name and Montreal/Quebec address" }
    },
    required: ["productType", "productNameFr", "productNameEn", "netWeight", "scentNotesFr", "scentNotesEn", "inciList", "companyAndAddress"]
  }
};

const evaluate_order_quote_cogs: FunctionDeclaration = {
  name: "evaluate_order_quote_cogs",
  description: "Run an internal COGS, finished stock vs production gap, 50% B2B deposit & cash-flow coverage check, material shortfall audit, and curing lead-time feasibility check on an incoming order/quote or custom line items.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      incomingOrderId: { type: Type.STRING, description: "ID or referenceCode of an existing incoming order/quote (optional)" },
      sku: { type: Type.STRING, description: "SKU to evaluate if evaluating ad-hoc (optional)" },
      quantity: { type: Type.NUMBER, description: "Quantity of kits/units (optional)" },
      province: { type: Type.STRING, description: "Canadian province code (e.g., QC, ON) for tax & Loi 96 check" },
      requestedDeliveryDate: { type: Type.STRING, description: "Target YYYY-MM-DD delivery date (optional)" },
      coBrandingOptions: {
        type: Type.ARRAY,
        items: { type: Type.STRING },
        description: "Optional add-on slugs (e.g., monogram-linen-band, embossed-arch-card, jesmonite-color-match)"
      }
    }
  }
};

const check_sku_bom_and_stock: FunctionDeclaration = {
  name: "check_sku_bom_and_stock",
  description: "Explode a Catalog SKU + quantity into exact raw ingredients and packaging BOM components and check current normalized inventory for shortfalls.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      sku: { type: Type.STRING, description: "Canonical SKU or product name (e.g. LJW-B2B-ARC-02, LJW-ECZ-BALM-100)" },
      quantity: { type: Type.NUMBER, description: "Number of units/boxes to check" }
    },
    required: ["sku", "quantity"]
  }
};

const stage_outbound_deliverable: FunctionDeclaration = {
  name: "stage_outbound_deliverable",
  description: "Stage an INTERNAL-ONLY deliverable (quote dossier, procurement restock alert, or portal/Loi 96 fulfillment pack) in the studio's Outbound Review Queue for Myrna's 1-click inspection. NEVER sends emails or messages externally.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      kind: {
        type: Type.STRING,
        enum: ["quote_proposal_ready", "procurement_shortfall", "portal_and_compliance_ready"],
        description: "Type of internal staging item"
      },
      referenceCode: { type: Type.STRING, description: "Reference code (e.g., LJW-B2B-9F2A1C)" },
      title: { type: Type.STRING, description: "Short internal title" },
      summary: { type: Type.STRING, description: "Concise internal summary" },
      markdownContent: { type: Type.STRING, description: "Full internal Markdown dossier or procurement shopping list" }
    },
    required: ["kind", "referenceCode", "title", "summary"]
  }
};

const ARTY_INTERNAL_OFFICE_GUARDRAILS = `
HARD OFFICE & PRODUCTION GUARDRAILS (NON-NEGOTIABLE):
1. STRICTLY INTERNAL ONLY — ZERO EXTERNAL CONTACT: You MUST NEVER send emails, SMS, webhooks, Stripe invoices, or external client replies. All quotes, dossiers, compliance packs, and procurement alerts are internal working artifacts staged exclusively for Myrna's review.
2. STAGING QUARANTINE: Any event or query tagged 'environment: staging' runs strictly in simulation/sandbox mode and MUST NEVER deduct real inventory, finished stock, or live accounting ledgers.
3. SPLIT QUOTE vs. PAID ORDER & HITL DISCIPLINE:
   - On quote_request / b2b_inquiry / b2b_sample_request / retail_preorder: Review stock & BOM, compute landed COGS & gross margin (70%+ floor), verify 50% B2B deposit & cash-flow coverage against direct materials+packaging COGS, verify cure lead-time, draft internal dossier & tentative dates — NEVER deduct inventory and NEVER record revenue.
   - On paid_order / retail_paid_order (verified only): Stage internal dossier, procurement shortfalls, and batch/deduction proposals for Myrna's HITL approval before committing physical stock deductions or production pours.
4. FULL COGS & ALL-COLLECTION FLUENCY: Always inspect the live Workshop Reference Tables (Catalog SKU -> Formulation & Packaging BOM Map, Standardized Inventory with unit costs & reorder floors, Pricing/Deposit/Margin/Cure Rules, and all collections: B2B, Eczema, Menopause/Say It Plain, Celestial). Never guess numbers when exact table figures are in context.`;

const AGENT_PROMPTS: Record<AgentRole, string> = {
  StudioLead: `You are the Lead Studio Director & Autonomous Office/Production Orchestrator for LJWellness, a B2B luxury botanical & architectural closing-gift atelier (serving builders, condo developers, realtors) plus specialized Eczema and Menopause (Say It Plain) botanical skincare lines.

  TEMPORAL CONTEXT: Current year is 2026.

  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}

  THE 12 LJWELLNESS STUDIO ROOMS & HUBS:
  1. Master Orchestration Room ('workshop')
  2. Task Room / Deliverables Board ('tasks')
  3. Studio Planner & Calendar ('planner')
  4. Formulation Lab & Recipe Library ('recipes')
  5. COGS & Financial Hub ('cogs' / 'ledger')
  6. Wholesale & Builders CRM ('wholesale' / 'corporate-accounts')
  7. Documents Hub ('documents-hub')
  8. Inventory & Materials Hub ('supplies' / 'inventory')
  9. Production Hub ('production')
  10. Collections Hub ('collections')
  11. Compliance Hub ('compliance' — Quebec Loi 96 / OQLF + Health Canada CNF)
  12. Storefront & Outbound Staging Queue ('storefront' — incoming orders/quotes & internal outbound review queue)

  OFFICE & PRODUCTION INTAKE WORKFLOW:
  Whenever reviewing an incoming order, quote request, or production request:
  1. Call 'evaluate_order_quote_cogs' or 'check_sku_bom_and_stock' to verify finished stock vs. production gap, raw+packaging BOM shortfalls, exact COGS, 50% B2B deposit & cash-flow coverage, and backward cure dates.
  2. Call 'create_asset' & 'stage_outbound_deliverable' (kind: 'quote_proposal_ready') with the complete internal Production & Costing Dossier Markdown for Myrna's #admin review.
  3. If raw botanicals, vessels, or packaging are short, create a procurement task ('create_task' assigned to Business/Formulator) and call 'stage_outbound_deliverable' (kind: 'procurement_shortfall').
  4. If province is QC or locale is fr/bilingual, ensure Quebec Loi 96 bilingual pack is staged via 'generate_french_compliance_pack'; if B2B development run (10+ units or condo/rental/builder), stage portal planning via 'create_development_portal'.
  5. Call 'add_event' to pencil cure milestones & earliest feasible ship dates onto Studio Planner.
  6. Call 'complete_task' when resolving pending tasks.
  CRITICAL COMMUNICATION & TOOL RULES:
  - If the user is simply greeting you, checking visibility ("do you see...", "are you able to see..."), or asking a status question ("what was completed?"), answer honestly in clear plain text WITHOUT firing any tools unless they ask you to create/evaluate/execute something.
  - Whenever you DO invoke a tool, ALWAYS write a clear plain-text message explaining what you are evaluating/creating and why. NEVER send a silent tool call without explanation.`,

  Formulator: `You are the Master Artisan Formulator & Cosmetic Chemist (Calyx) for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}

  AUTONOMOUS PRODUCTION & LAB DIRECTIVES:
  - Inspect exact ingredient weights (g/ml), cure windows (35-56d cold-process/stone-cast, 14d wax melts, 5-14d serums/balms), and standardized inventory stock/reorder floors in Workshop State.
  - When reviewing an order or scaling a batch: use 'check_sku_bom_and_stock', 'scale_formulation', 'calculate_saponification', or 'audit_formulation_safety'.
  - If raw botanicals or vessels/packaging are short, log a 'create_task' (tagged [PROCUREMENT]) and 'stage_outbound_deliverable' (kind: 'procurement_shortfall') rather than deducting unapproved stock.
  - When locale is fr/bilingual or province is QC, invoke 'generate_french_compliance_pack' (Quebec Loi 96 / OQLF + Health Canada INCI).
  - Always schedule cure completion dates with 'add_event' and record formulation sheets with 'create_asset'.`,

  Business: `You are the Commercial Director & B2B Procurement Lead for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}

  AUTONOMOUS COMMERCIAL & PROCUREMENT DIRECTIVES:
  - Oversee B2B Builder/Developer/Realtor accounts, quote feasibility, volume tier rules (1–9, 10–24, 25–49, 50+), 50% B2B upfront deposit + $95 custom Jesmonite setup fee, and packaging/raw material restock vendor lead times.
  - For quote requests: log/review account ('create_corporate_account'), stage internal quote dossier ('create_asset' + 'stage_outbound_deliverable'), schedule tentative handover deadlines ('add_event'), and generate procurement restock shopping lists if any packaging or botanical SKU is short. NEVER email clients directly.`,

  Marketing: `You are the B2B Luxury Brand Storyteller & Bilingual Positioning Strategist for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}
  - Craft architectural homeowner handover storytelling, QR development welcome copy, A3 binder briefs, and collection positioning across B2B, Eczema, and Menopause (Say It Plain) lines — saved internally via 'create_asset', 'create_campaign', or 'create_development_portal'. Never transmit externally.`,

  NicheExpert: `You are the Luxury Real Estate Gifting, Architectural Sensory & B2B Curation Specialist for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}
  - Design box editions (Uniform Development QR, Custom Single-Buyer, Builder Wholesale Run), Jesmonite vessel & scent pairings, and homeowner vs renter audience positioning with accurate BOM & COGS awareness via 'create_asset' and 'create_development_portal'.`,

  WealthAdvisor: `You are the Studio Profitability & COGS Finance Analyst (Vesper) for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}

  COSTING, MARGIN & 50% DEPOSIT MANDATES:
  - Calculate exact landed Unit COGS (raw materials + vessels/packaging + co-branding add-ons + $35/hr direct labor + studio overhead + payment processing awareness), Total COGS, Net Revenue, Gross Profit ($), and Gross Margin (%) across ALL tracks (B2B, Eczema, Menopause, Celestial).
  - Enforce the **70%+ gross margin floor** (75% target on custom B2B) and alert immediately if a coupon or tier discount compresses margin below 70%.
  - On B2B quotes/orders: compute exact **50% B2B deposit** (including $95 custom Jesmonite setup fee when applicable + Canadian provincial tax preview: QC 5% TPS + 9.975% TVQ, ON 13% HST, etc.) AND explicitly verify whether the 50% deposit covers 100% of direct raw materials & packaging COGS.
  - NEVER record revenue ('update_finance') on quote requests or staging simulations! Always save internal financial dossiers using 'create_asset' / 'evaluate_order_quote_cogs'.`,

  Mentor: `You are the B2B Brand Advisor & Craft Mentor for LJWellness.
  TEMPORAL CONTEXT: Current year is 2026.
  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}
  - Protect margin discipline, sustainable curing lead-times, and burnout-free batch pacing across all 12 rooms. Capture strategic frameworks in 'create_smart_note' and 'create_asset'.`,

  System: `You are the LJWellness Studio Intelligence System Layer enforcing strict internal-only operation, staging sandbox isolation, idempotency, and HITL stock/accounting guardrails.`
};

export function buildWorkshopStateSummary(
  state: any,
  agreedCatalog?: StorefrontAgreementCatalog,
): string {
  if (!state) return '';
  const catalog = agreedCatalog || buildDefaultAgreementCatalog();
  const tasksList = Array.isArray(state.tasks) ? state.tasks : [];
  const pendingTasks = tasksList.filter((t: any) => t.status !== 'completed');
  const smartNotesList = Array.isArray(state.smartNotes) ? state.smartNotes : [];
  const eventsList = Array.isArray(state.planner?.events) ? state.planner.events : [];
  const corporateAccountsList = Array.isArray(state.corporateAccounts) ? state.corporateAccounts : [];
  const portalsList = Array.isArray(state.developmentPortals) ? state.developmentPortals : [];
  const incomingOrdersList = Array.isArray(state.incomingOrders) ? state.incomingOrders : [];
  const outboundQueueList = Array.isArray(state.outboundQueue) ? state.outboundQueue : [];

  const stdInventory = auditStudioInventory(Array.isArray(state.inventory) ? state.inventory : []);
  const skuBoms = buildSkuBomCatalog(catalog, Array.isArray(state.formulations) ? state.formulations : []);
  const cogsSummary = evaluateCollectionAndFormulationCogs(state, catalog);

  const assetsList = Array.isArray(state.assets) ? state.assets : [];
  const documentsList = Array.isArray(state.documents) ? state.documents : [];
  const prioritizedAssets = [...assetsList].sort((a: any, b: any) => {
    const aPri = /manifesto|blueprint|b2b|pricing|margin|cogs|dossier/i.test(a.title || '') ? 1 : 0;
    const bPri = /manifesto|blueprint|b2b|pricing|margin|cogs|dossier/i.test(b.title || '') ? 1 : 0;
    return bPri - aPri;
  });

  return `
Current Workshop State (Live Year: 2026 | INTERNAL STUDIO OFFICE ONLY):
- Artisan: ${state.profile?.artisan?.name || 'Master Formulator'} (${state.profile?.artisan?.experience || '14 Years'})
- Studio: ${state.profile?.name || 'LJWellness'} (${state.profile?.niche || 'B2B Luxury Botanical & Skincare Atelier'})
- Finances: Balance $${state.finances?.balance || 0} | Revenue $${state.finances?.revenue || 0} | Expenses $${state.finances?.expenses || 0} | Target Margin: ${state.profile?.targetMargin || 75}%

LOOKUP TABLE 1 — STANDARDIZED INVENTORY WITH UNIT COSTS & REORDER FLOORS (${stdInventory.length} items):
${stdInventory.map((i) => `  * [${i.category}] ${i.item}: ${i.normalizedStock} ${i.normalizedUnit} (orig: ${i.originalStock} ${i.originalUnit}) | Cost: $${i.costPerNormalizedUnit}/${i.normalizedUnit} ($${i.costPerOriginalUnit}/${i.originalUnit}) | Reorder Floor: ${i.reorderThreshold} ${i.normalizedUnit}${i.lowStock ? ' [LOW STOCK]' : ''}`).join('\n') || '  (Inventory empty)'}

LOOKUP TABLE 2 — FORMULATIONS WITH EXACT WEIGHTS, CURE WINDOWS & UNIT RAW COSTS (${cogsSummary.formulations.length} formulas):
${(state.formulations || []).map((f: any) => {
  const cogsRow = cogsSummary.formulations.find((r) => r.id === f.id || r.name === f.name);
  const ingText = (f.ingredients || []).map((ing: any) => `${ing.name} (${ing.amount}${ing.unit})`).join(', ');
  return `  * [ID: ${f.id}] ${f.name} | Cure: ${f.curingTimeDays}d | Yield: ${f.batchSize}${f.batchUnit} | Est. Unit Raw Cost: $${cogsRow?.estimatedUnitRawCostCad ?? 0} CAD | Ingredients: ${ingText}`;
}).join('\n') || '  (No formulations stored)'}

LOOKUP TABLE 3 — CATALOG SKU -> FORMULATION, PACKAGING BOM, COGS & 50% B2B DEPOSIT MATRIX (${skuBoms.length} SKUs):
${skuBoms.slice(0, 26).map((b) => {
  const cogs = cogsSummary.skus.find((s) => s.sku === b.sku);
  const pkgTxt = b.packagingBom.map((pk) => `${pk.quantityPerUnit}x ${pk.itemName}`).join(' + ');
  const rawTxt = b.rawBom.map((r) => `${r.amountPerUnit}${r.unit} ${r.itemName}`).join(', ');
  return `  * ${b.sku} [${b.track.toUpperCase()}] ${b.productName} (${b.finishedUnitWeight}) | Cure: ${b.cureTimeDays}d | Price: $${cogs?.priceCad ?? b.defaultUnitPriceCad} (70% Floor Price: $${cogs?.recommendedPrice70PctCad ?? 0}) | Unit COGS: $${cogs?.unitTotalCogsCad ?? 0} (Raw $${cogs?.unitRawCostCad ?? 0} + Pkg $${cogs?.unitPackagingCostCad ?? 0} + Labor/OH $${cogs?.unitLaborOverheadCad ?? 0}) | Margin: ${cogs?.grossMarginPct ?? 0}% | 50% Deposit: $${cogs?.b2b50PctDepositPerUnitCad ?? 0}/unit | Pkg BOM: [${pkgTxt}] | Raw BOM: [${rawTxt}]`;
}).join('\n')}

STUDIO PRICING, DEPOSIT & LEAD-TIME RULES:
- Currency: CAD | B2B Upfront Deposit: ${STUDIO_PRICING_RULES.b2bDepositPct}% (must verify if deposit covers 100% of direct raw+pkg COGS; +$95 setup fee for jesmonite-color-match)
- Gross Margin Floor: ${STUDIO_PRICING_RULES.grossMarginFloorPct}% (Custom Target: ${STUDIO_PRICING_RULES.customTargetMarginPct}%) | Direct Labor: $${STUDIO_PRICING_RULES.hourlyLaborRateCad}/hr (${STUDIO_PRICING_RULES.defaultMinutesPerUnit} min/unit) + $${STUDIO_PRICING_RULES.allocatedOverheadPerUnitCad}/unit studio overhead
- Volume Tiers: ${STUDIO_PRICING_RULES.volumeTiers.map((t) => `${t.label}: ${t.discountPctOffBase}% off, target ${t.targetMarginPct}% margin (${t.boxEdition})`).join(' | ')}
- Cure Windows: Cold-Process ${STUDIO_PRICING_RULES.cureWindowsDays.coldProcessSoap}d | Stone-Cast ${STUDIO_PRICING_RULES.cureWindowsDays.stoneCastSoap}d | Soy Melts ${STUDIO_PRICING_RULES.cureWindowsDays.botanicalWaxMelts}d | Serums/Balms ${STUDIO_PRICING_RULES.cureWindowsDays.serumsAndBalms}d | Fulfillment Pack Buffer +${STUDIO_PRICING_RULES.packagingAndFulfillmentBufferDays}d

ACTIVE COLLECTIONS & COGS SNAPSHOT:
${(state.collections || []).map((c: any) => `  * ${c.name} (${c.stage}) — ${(c.products || []).map((p: any) => `${p.name}: $${p.price} (Stock: ${p.stock})`).join(', ')}`).join('\n') || '  (N/A)'}

LIVE INCOMING ORDERS & QUOTES QUEUE (${incomingOrdersList.length} records):
${incomingOrdersList.slice(0, 15).map((o: IncomingOrderQuote) => {
  const itemsTxt = (o.lineItems || []).map((li) => `${li.quantity}x ${li.sku || 'SKU'} ${li.productName} ($${li.unitPrice ?? 0})`).join(', ');
  const shortfallsTxt = (o.evaluation?.shortfalls || []).slice(0, 6).map((s) => `${s.itemName} -${s.shortfallQty}${s.unit}`).join('; ');
  return `  * [ID: ${o.id} | ${o.environment.toUpperCase()} | ${o.requestType} | ${o.status}] ${o.referenceCode} — ${o.client.companyName} (${o.client.contactPerson}, ${o.province || 'CA'}, ${o.locale}) | Items: [${itemsTxt}]${(o as any).coBrandingOptions?.length ? ` | Co-Branding: [${(o as any).coBrandingOptions.join(', ')}]` : ''}${o.timeline?.requestedDeliveryDate ? ` | Requested Ship: ${o.timeline.requestedDeliveryDate}` : ''} | Net: $${o.evaluation?.netRevenueCad ?? o.payment?.subtotal ?? 0} | COGS: $${o.evaluation?.totalCogsCad ?? 0} (${o.evaluation?.grossMarginPct ?? 0}% margin) | 50% Deposit: $${o.evaluation?.b2bDepositRequiredCad ?? 0} (Covers Direct COGS: ${o.evaluation?.b2bDepositCoversDirectCogs ? 'YES' : 'NO'}) | Shortfalls (${o.evaluation?.shortfalls?.length ?? 0}): ${shortfallsTxt || 'None'} | Earliest Safe Ship: ${o.evaluation?.earliestPossibleDeliveryDate || 'TBD'}`;
}).join('\n') || '  (No incoming storefront orders/quotes yet)'}

INTERNAL OUTBOUND REVIEW QUEUE — ZERO EXTERNAL SEND (${outboundQueueList.length} items):
${outboundQueueList.slice(0, 12).map((q: any) => `  * [${q.kind} | ${q.status}] ${q.referenceCode}: ${q.title} — ${q.summary || ''}`).join('\n') || '  (Queue empty)'}

DOCUMENTS HUB, B2B MANIFESTO & STRATEGY ASSETS (${assetsList.length} assets, ${documentsList.length} commercial docs):
${prioritizedAssets.slice(0, 15).map((a: any) => `  * [${a.type || 'doc'} | Author: ${a.author || 'Studio'}] ${a.title}: ${String(a.content || '').replace(/\s+/g, ' ').slice(0, 260)}`).join('\n') || '  (No saved assets)'}
${documentsList.slice(0, 8).map((d: any) => `  * [Commercial ${d.type || 'quote'} | ${d.status || 'draft'}] ${d.title} (${d.clientName || 'Client'}, $${d.amount || 0})`).join('\n') || ''}

- Tasks & Directives (${pendingTasks.length} Pending, ${tasksList.length} Total):
${tasksList.slice(0, 20).map((t: any) => `  * [ID: ${t.id}] ${t.title} (Assigned: ${t.assignedTo}, Priority: ${t.priority}, Status: ${t.status}) - ${t.description}`).join('\n') || '  (None)'}
- Studio Planner Schedule (${eventsList.length} Scheduled Events):
${eventsList.slice(0, 12).map((e: any) => `  * [${e.date}] ${e.title} (${e.type || 'production'})`).join('\n') || '  (None)'}
- SMART Notebook (${smartNotesList.length}): ${smartNotesList.map((n: any) => `${n.title} (${n.status})`).join(', ') || 'None'}
- B2B CRM Accounts (${corporateAccountsList.length}): ${corporateAccountsList.map((a: any) => `${a.companyName} (${a.accountType}, ${a.status})`).join(', ') || 'None'}
- QR Portals (${portalsList.length}): ${portalsList.map((p: any) => `${p.developmentName} (/portal/${p.slug})`).join(', ') || 'None'}
- Production Batches: ${state.productionBatches?.filter((b: any) => b.status !== 'finished').map((b: any) => `${b.batchName} (${b.status}, Yield: ${b.expectedYield})`).join(', ') || 'None'}
`;
}

export async function getAgentResponseServer(
  role: AgentRole,
  context: string,
  history: Message[],
  state?: any,
  agreedCatalog?: StorefrontAgreementCatalog,
) {
  // Ordered cascade of verified free-tier Gemini text models per @google/genai guidelines
  const modelCascade = [
    "gemini-4-hydrogen",
    "gemini-3.1-flash-lite",
    "gemini-2.5-flash"
  ];

  const formattedHistory = history.map(m => `${m.sender}: ${m.content}`).join('\n');
  const stateSummary = buildWorkshopStateSummary(state, agreedCatalog);

  const safeContext = context;
  const cleanContext = safeContext.trim().toLowerCase();
  const isGreeting = /^(hello|hi|hey|howdy|greetings|good\s+morning|good\s+afternoon|good\s+evening|yo|sup|what's\s+up)\b/i.test(cleanContext) ||
                     cleanContext.includes("hello team") || cleanContext.includes("hi team") || cleanContext.includes("i said hello");
  const isReadOnlyCheck =
    !isGreeting &&
    /\b(do you see|can you see|are you able to see|did you (just )?receive|can you locate|what was (just )?completed|why did you)\b/i.test(cleanContext) &&
    !/\b(create|draft|generate|run|execute|make|build|update)\b/i.test(cleanContext);

  const toolConstraint = isGreeting
    ? `\n[CRITICAL RULE] The user is simply saying hello, greeting the team, or checking in. You MUST NOT use any tools or make any function calls under any circumstances. Greet them back warmly as ${role} and ask how you can assist the studio today.`
    : isReadOnlyCheck
      ? `\n[CRITICAL RULE — VISIBILITY / STATUS QUESTION] The user is asking what you can currently see or what happened. Answer clearly and honestly in plain text using the Live Workshop State above WITHOUT calling any tools in this turn.`
      : `\n[CRITICAL AUTONOMOUS EXECUTION DIRECTIVE — EXPLAIN FIRST, THEN USE TOOLS]
You are an autonomous specialist operating inside the 12 rooms of LJWellness Studio.
1. ALWAYS include a clear plain-text response explaining what you found and which tool(s) you are calling (and why). NEVER return an empty message alongside a tool call!
2. Saying in text that you formulated a recipe, created an asset, completed a directive, or added an event to the calendar WITHOUT calling the corresponding tool is a critical system failure.
You MUST invoke the tools in this turn when action is requested:
- When fulfilling a task or directive: call 'complete_task' (or 'batch_complete_tasks') with the specific 'taskId', 'completionNotes', and 'actualOutcome' so the Task Room marks it completed.
- When creating a formula or recipe: call 'create_formulation' to store it in the Recipe Library, AND call 'add_event' to schedule its batch cure completion date on the Studio Planner Calendar!
- When writing marketing copy, strategies, SOPs, financial analyses, or research: call 'create_asset' with rich Markdown content so it is saved directly to the Documents Hub.
- When planning schedules, launches, wholesale deadlines, cure windows, or B2B handover milestones: call 'add_event' with the specific date (YYYY-MM-DD), title, and type.
- If capturing strategic breakthroughs or B2B plans: call 'create_smart_note'.
- If managing stock: call 'update_inventory'. If managing verified paid finances: call 'update_finance'.`;
  
  const prompt = `
TEMPORAL BASELINE: Current Year is 2026. Date: ${new Date().toISOString().split('T')[0]}.

${stateSummary}

Context: ${safeContext}

History:
${formattedHistory}

Current Request: ${safeContext}

${toolConstraint}

Respond as the ${role}. 
If you need to take action, capture SMART notes, or complete directives, invoke the provided tools.
`;

  const tools = (isGreeting || isReadOnlyCheck)
    ? []
    : [{ functionDeclarations: [
        create_smart_note,
        update_smart_note,
        delete_smart_note,
        convert_note_to_directives,
        complete_task,
        batch_complete_tasks,
        update_task_status,
        create_task, 
        update_inventory, 
        create_asset, 
        update_finance, 
        create_project, 
        create_wholesale_client, 
        create_wholesale_order, 
        create_prospect, 
        log_outreach, 
        update_prospect_status, 
        create_campaign, 
        update_campaign_budget, 
        analyze_market_trends, 
        optimize_formula, 
        create_batch,
        create_formulation,
        calculate_saponification,
        audit_formulation_safety,
        scale_formulation,
        migrate_recipe_asset,
        add_event,
        delegate_to_agent,
        delete_record,
        create_corporate_account,
        create_development_portal,
        generate_french_compliance_pack,
        evaluate_order_quote_cogs,
        check_sku_bom_and_stock,
        stage_outbound_deliverable
      ] }];

  for (let i = 0; i < modelCascade.length; i++) {
    const currentModel = modelCascade[i];
    // Attempt with retry on transient network 503
    for (let attempt = 0; attempt < 2; attempt++) {
      try {
        const response = await ai.models.generateContent({
          model: currentModel,
          contents: prompt,
          config: {
            systemInstruction: AGENT_PROMPTS[role],
            tools: tools
          }
        });
        
        let text = response.text || "";
        const rawFunctionCalls = response.functionCalls || [];

        if (!text.trim() && rawFunctionCalls.length > 0) {
          const actionSummary = rawFunctionCalls
            .map((f: any) => {
              const label = String(f.name || "action").replace(/_/g, " ");
              const target = f.args?.incomingOrderId || f.args?.referenceCode || f.args?.sku || f.args?.title || "";
              return target ? `${label} (${target})` : label;
            })
            .join(", ");
          text = `Reviewing your studio data and initiating: ${actionSummary}. Check the logs and Documents/Tasks hubs for the resulting breakdown.`;
        } else if (!text.trim()) {
          text = "I have checked your studio records. Let me know how you would like to proceed.";
        }
        
        return { 
          text, 
          functionCalls: rawFunctionCalls.length > 0 ? rawFunctionCalls : undefined,
          isFallback: false,
          model: currentModel
        };
      } catch (error: any) {
        const isTransient = error?.message?.includes('503') || error?.message?.includes('UNAVAILABLE') || error?.message?.includes('high demand');
        if (attempt === 0 && isTransient) {
          await new Promise(resolve => setTimeout(resolve, 350));
          continue;
        }
        console.warn(`[Artisan Engine] Model ${currentModel} (attempt ${attempt + 1}) encountered an issue. Transitioning to next candidate...`);
        break;
      }
    }
  }

  // Graceful conversational response if all cloud endpoints are momentarily saturated
  const fallback = generateContextualArtisanFallback(role, safeContext, state);
  return {
    text: fallback.text,
    functionCalls: fallback.functionCalls,
    isFallback: true
  };
}

function generateContextualArtisanFallback(role: AgentRole, context: string, state?: any): { text: string; functionCalls?: any[] } {
  const query = context.toLowerCase();
  const tasksList = state?.tasks && Array.isArray(state.tasks) ? state.tasks : [];
  
  // Check if this was a directive execution prompt
  const taskMatch = context.match(/EXECUTE DIRECTIVE NOW:\s*"([^"]+)"/i) || context.match(/directive:\s*"([^"]+)"/i);
  let matchedTask = taskMatch ? tasksList.find((t: any) => t.title.toLowerCase().includes(taskMatch[1].toLowerCase())) : null;
  if (!matchedTask) {
    matchedTask = tasksList.find((t: any) => t.assignedTo === role && t.status !== 'completed') || tasksList.find((t: any) => t.status !== 'completed');
  }

  const isExecutionRequest = /execute|directive|fulfill|task|formulate|calculate|scale|recipe/i.test(query);

  if (role === 'Formulator' || /foundation|seasalt|brine|serum|butter|formula|recipe|ingredient|soap|saponif/i.test(query)) {
    const text = `### 🧪 Master Formulation Specification: The Foundation Collection
*Formulated by Master Cosmetic Chemist & Botanical Formulator*

#### 1. Seasalt & Pacific Brine Cold Process Bar (1,000g Batch)
- **Saponification Matrix (8% Superfat | 2.2:1 Water:Lye):**
  - Organic Extra Virgin Olive Oil: 400g (40%)
  - Raw Unrefined Coconut Oil: 250g (25%)
  - Fair-Trade Shea Butter: 200g (20%)
  - Cold-Pressed Castor Oil: 100g (10%)
  - Golden Jojoba Oil: 50g (5%)
- **Lye Solution:** 137g Pure Sodium Hydroxide (NaOH) dissolved in 300g Mineral Ocean Brine / Distilled Water.
- **Trace Additives:** 150g Ultra-Fine Pacific Grey Sea Salt, 20g French Green Clay, 30g Essential Oil Chord (Atlantic Cedarwood, Sweet Marjoram, Wild Lavender).
- **INS Hardness Rating:** 148 | **Conditioning:** 54 | **Cure Time:** 35 Days.

#### 2. Restorative Botanical Lipid Body Serum (500ml Batch)
- **Phase A (Active Botanical Lipid Base - 85%):**
  - Plant-Derived Olive Squalane: 225ml (45%)
  - Cold-Pressed Organic Rosehip Seed Oil (High Linoleic): 125ml (25%)
  - Golden Jojoba Esters: 75ml (15%)
- **Phase B (Active Botanical Phyto-Nutrients - 12%):**
  - Sea Buckthorn Fruit CO2 Extract: 30ml (6%)
  - Bakuchiol Phyto-Retinol Active: 15ml (3%)
  - Evening Primrose Seed Oil: 15ml (3%)
- **Phase C (Antioxidant & Scent Chord - 3%):**
  - Non-GMO Mixed Tocopherols (Vitamin E): 5ml (1%)
  - Artisan Botanical Essence (Bergamot FCF, Frankincense, Blue Tansy): 10ml (2%)

#### 3. Whipped Kokum & Nilotica Body Butter (800g Batch)
- **Phase A (Heated Anhydrous Lipid Matrix):**
  - Raw Indian Kokum Butter (High Stearic/Hardness): 320g (40%)
  - East African Nilotica Shea Butter (Silky/High Oleic): 280g (35%)
  - Sweet Almond Carrier Oil: 144g (18%)
- **Phase B (Cool Down Whipping Matrix at 32°C):**
  - Organic Arrowroot Powder (Matte Silk Finish): 32g (4%)
  - Rosemary Leaf CO2 Extract (Antioxidant): 8g (1%)
  - Neroli & Santalum Essential Oil: 16g (2%)
- **Process:** Melt to 70°C, rapid cool in ice bath to 25°C, high-shear whip for 12 mins until double volume cloud texture.

*Note: All precision formulas have been structured with full INCI compliance, safety margins, and batch scaling specs.*`;

    const functionCalls: any[] = [];
    if (isExecutionRequest && matchedTask) {
      functionCalls.push({
        name: 'complete_task',
        args: {
          taskId: matchedTask.id,
          actualOutcome: text,
          completionNotes: 'Formulations drafted, verified with full INCI compliance, and scheduled onto calendar.'
        }
      });
      functionCalls.push({
        name: 'create_asset',
        args: {
          title: `Master Formulation: ${matchedTask.title}`,
          content: text,
          type: 'recipe',
          author: 'Formulator'
        }
      });
    }

    functionCalls.push({
      name: 'create_formulation',
      args: {
        name: 'Seasalt & Pacific Brine Bar (Bespoke Formula)',
        ingredients: [
          { name: 'Organic Extra Virgin Olive Oil', amount: 400, unit: 'g' },
          { name: 'Raw Unrefined Coconut Oil', amount: 250, unit: 'g' },
          { name: 'Fair-Trade Shea Butter', amount: 200, unit: 'g' },
          { name: 'Cold-Pressed Castor Oil', amount: 100, unit: 'g' },
          { name: 'Golden Jojoba Oil', amount: 50, unit: 'g' },
          { name: 'Ultra-Fine Pacific Grey Sea Salt', amount: 150, unit: 'g' },
          { name: 'Sodium Hydroxide (NaOH)', amount: 137, unit: 'g' },
          { name: 'Mineral Ocean Brine / Pure Water', amount: 300, unit: 'g' }
        ],
        instructions: 'Dissolve NaOH into cold ocean brine. Melt shea butter and plant oils at 105°F. Pulse with stick blender to light trace. Fold in fine Pacific sea salt and aromatic accords. Pour into silicone individual cavity molds. Unmold within 14 hours and cure for 35 days.',
        curingTimeDays: 35,
        batchSize: 1000,
        batchUnit: 'g'
      }
    });

    functionCalls.push({
      name: 'add_event',
      args: {
        title: 'Seasalt & Brine Bar - Batch Cure Complete',
        date: new Date(Date.now() + 35 * 86400000).toISOString().split('T')[0],
        type: 'production',
        category: 'Soap',
        description: 'Full 35-day cold process bar cure window complete. Ready for pH verification, packaging, and fulfillment.'
      }
    });

    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };
  }

  if (/marketing|campaign|instagram|social|story|launch|audience/i.test(query)) {
    const text = `### 📣 Campaign Strategy & Storytelling
**Focus Directive:** ${context}

**Suggested 3-Phase Rollout:**
1. **Teaser / Behind the Craft (Days 1–3):** Short-form video highlighting raw botanical sourcing and small-batch pouring.
2. **Collection Drop / Early Access (Day 4):** Direct email blast to VIP and wholesale partners offering complimentary sampling.
3. **Community Validation (Days 5–7):** Share behind-the-scenes curing logs and limited edition batch counters.`;

    const functionCalls: any[] = [];
    if (isExecutionRequest && matchedTask) {
      functionCalls.push({
        name: 'complete_task',
        args: {
          taskId: matchedTask.id,
          actualOutcome: text,
          completionNotes: 'Campaign strategy documented and staged for release.'
        }
      });
      functionCalls.push({
        name: 'create_asset',
        args: {
          title: `Marketing Strategy: ${matchedTask.title}`,
          content: text,
          type: 'marketing',
          author: role
        }
      });
    }

    functionCalls.push({
      name: 'create_campaign',
      args: {
        name: matchedTask ? matchedTask.title : 'Slow Botanicals Autumn Campaign',
        platform: 'Instagram',
        budget: 500,
        notes: 'Omni-channel sensory storytelling drop.',
        content: text
      }
    });

    functionCalls.push({
      name: 'add_event',
      args: {
        title: `Campaign Launch Drop: ${matchedTask ? matchedTask.title : 'Autumn Botanical Collection'}`,
        date: new Date(Date.now() + 7 * 86400000).toISOString().split('T')[0],
        type: 'marketing',
        category: 'General',
        description: 'Public release and VIP newsletter dispatch scheduled on Studio Planner.'
      }
    });

    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };
  }

  if (/cost|price|profit|margin|finance|wholesale|b2b/i.test(query)) {
    const margin = state?.profile?.targetMargin || 65;
    const text = `### 💎 Profitability & Unit Economics Analysis
**Financial Parameter Check:**
- **Target Studio Gross Margin:** ${margin}%
- **Wholesale Price Standard:** 50% of MSRP (ensuring 2.0x keystone pricing)
- **Direct Material Buffer:** Add 10–12% overhead for eco-luxe packaging and compliance labels.

*Recommendation:* Review supplier raw-material tier pricing for bulk savings on your highest volume inputs.`;

    const functionCalls: any[] = [];
    if (isExecutionRequest && matchedTask) {
      functionCalls.push({
        name: 'complete_task',
        args: {
          taskId: matchedTask.id,
          actualOutcome: text,
          completionNotes: 'Financial analysis verified against studio target margins.'
        }
      });
      functionCalls.push({
        name: 'create_asset',
        args: {
          title: `Financial Analysis: ${matchedTask.title}`,
          content: text,
          type: 'finance',
          author: 'WealthAdvisor'
        }
      });
    }

    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };
  }

  const defaultText = `Hello! I'm here as ${role} for ${state?.profile?.name || 'the studio'}. I've reviewed your note regarding "${context}". 

Let's collaborate on your recipes, inventory planning, campaigns, or calendar scheduling. Feel free to give me a specific directive or ask me to draft a new formulation!`;

  const defaultCalls: any[] = [];
  if (isExecutionRequest && matchedTask) {
    defaultCalls.push({
      name: 'complete_task',
      args: {
        taskId: matchedTask.id,
        actualOutcome: defaultText,
        completionNotes: `Directive resolved and recorded by ${role}.`
      }
    });
    defaultCalls.push({
      name: 'create_asset',
      args: {
        title: `${matchedTask.title} (Execution Record)`,
        content: defaultText,
        type: 'strategy',
        author: role
      }
    });
  }

  return { text: defaultText, functionCalls: defaultCalls.length > 0 ? defaultCalls : undefined };
}

/**
 * Headless StudioLead "Wake-Up" Orchestrator invoked automatically on webhook receipt or 1-click re-run.
 * Combines deterministic COGS/BOM/50%-deposit/cure math with optional Gemini StudioLead executive narrative.
 * Strictly internal-only: NEVER sends emails, SMS, webhooks, or external invoices.
 */
export async function runHeadlessStudioLeadIntake(
  order: IncomingOrderQuote,
  stateSnapshot?: any,
  agreedCatalog?: StorefrontAgreementCatalog,
  options?: { skipAi?: boolean; forceAi?: boolean },
): Promise<{
  evaluation: ReturnType<typeof evaluateIncomingOrderOrQuote>;
  agentNarrative: string;
  model?: string;
  toolsSuggested: Array<{ name: string; args: Record<string, any> }>;
}> {
  const evaluation = evaluateIncomingOrderOrQuote(order, stateSnapshot, agreedCatalog);
  const catalog = agreedCatalog || buildDefaultAgreementCatalog();
  const stateWithOrder = {
    ...(stateSnapshot || {}),
    incomingOrders: [order, ...((stateSnapshot?.incomingOrders || []).filter((o: any) => o.id !== order.id))],
  };

  let agentNarrative = [
    `[StudioLead Internal Dossier — ${order.referenceCode}]`,
    `Mode: ${order.environment === 'staging' ? 'STAGING SANDBOX' : order.requestType.toUpperCase()}`,
    `Net Revenue: $${evaluation.netRevenueCad?.toFixed(2)} CAD | Total COGS: $${evaluation.totalCogsCad.toFixed(2)} CAD | Margin: ${evaluation.grossMarginPct.toFixed(1)}%`,
    `Required ${evaluation.depositPct}% Deposit: $${evaluation.b2bDepositRequiredCad.toFixed(2)} CAD (Covers 100% Direct Raw+Pkg COGS: ${evaluation.b2bDepositCoversDirectCogs ? 'YES' : 'NO'})`,
    `Shortfalls: ${evaluation.shortfalls.length} item(s) | Earliest Safe Ship Date: ${evaluation.earliestPossibleDeliveryDate}`,
    `Notice: Internal dossier staged for Myrna's review. Zero external emails or client replies sent.`,
  ].join('\n');

  let usedModel: string | undefined = 'deterministic-studio-engine';
  const toolsSuggested: Array<{ name: string; args: Record<string, any> }> = [];
  const shouldSkipAi = Boolean(options?.skipAi ?? (order.environment === 'staging' && !options?.forceAi));

  if (!shouldSkipAi && process.env.GEMINI_API_KEY && process.env.NODE_ENV !== 'test') {
    const promptText = [
      `HEADLESS ARTY WAKE-UP INTAKE: Analyze inbound ${order.environment} ${order.requestType} [${order.referenceCode}].`,
      `Client: ${order.client.companyName} (${order.client.contactPerson}, ${order.client.province || 'CA'}, Locale: ${order.locale}).`,
      `Line Items: ${order.lineItems.map((l) => `${l.quantity}x ${l.sku} ${l.productName} ($${l.unitPrice || 0})`).join('; ')}.`,
      `Deterministic Evaluation Snapshot:`,
      `- Dossier Status: ${evaluation.dossierStatus}`,
      `- Finished Ready: ${evaluation.totalFinishedStockAvailable} units | Pour Needed: ${evaluation.totalUnitsToProduce} units`,
      `- Total COGS: $${evaluation.totalCogsCad.toFixed(2)} (Direct Materials+Pkg: $${evaluation.directMaterialsAndPackagingCogsCad?.toFixed(2)})`,
      `- Net Revenue: $${evaluation.netRevenueCad?.toFixed(2)} | Margin: ${evaluation.grossMarginPct.toFixed(1)}% (Floor 70%: ${evaluation.meetsMarginFloor ? 'PASS' : 'LOW'})`,
      `- B2B ${evaluation.depositPct}% Deposit: $${evaluation.b2bDepositRequiredCad.toFixed(2)} | Covers 100% Direct COGS: ${evaluation.b2bDepositCoversDirectCogs ? 'YES' : 'SHORT by $' + evaluation.depositCashFlowGapCad}`,
      `- Shortfalls: ${evaluation.shortfalls.map((s) => `${s.itemName}: short ${s.shortfallQty}${s.unit}`).join('; ') || 'None'}`,
      `- Cure / Earliest Ship Date: ${evaluation.earliestPossibleDeliveryDate} (Requested: ${evaluation.requestedDeliveryDate || 'None'}; Feasible: ${evaluation.cureFeasible})`,
      `Provide a concise 4-bullet internal executive briefing for Myrna ONLY (never draft an external send action). Do not contradict the deterministic figures above.`,
    ].join('\n');

    try {
      const geminiRes = await getAgentResponseServer('StudioLead', promptText, [], stateWithOrder, catalog);
      if (geminiRes?.text && !geminiRes.isFallback) {
        agentNarrative = geminiRes.text;
        usedModel = geminiRes.model;
      }
      if (Array.isArray(geminiRes?.functionCalls)) {
        for (const fc of geminiRes.functionCalls) {
          if (fc?.name && !/email|send_external|notify_client/i.test(fc.name)) {
            toolsSuggested.push({ name: fc.name, args: fc.args || {} });
          }
        }
      }
    } catch (err) {
      console.warn('[StudioLead Headless] Falling back to deterministic internal briefing:', err);
    }
  }

  return {
    evaluation,
    agentNarrative,
    model: usedModel,
    toolsSuggested,
  };
}

