#!/usr/bin/env python3
"""
MiniMax 500-Agent Swarm — Sunaiva Talking Widget Content Generation
Fires 500 MiniMax M2.5 agents via OpenRouter across 10 content categories.

USAGE:
    PYTHONUNBUFFERED=1 python /mnt/e/genesis-system/scripts/minimax500_swarm.py

OUTPUTS:
    /mnt/e/genesis-system/swarm-output/session22/minimax500/
        category_01_widget_customization/agent_001.json ... agent_050.json
        category_02_faq_content/agent_051.json ... agent_100.json
        ...
        category_10_competitive_comparison/agent_451.json ... agent_500.json
        SWARM_REPORT.md
        all_results.jsonl

Author: Genesis System
Date: 2026-02-16
"""

import os
import sys
import json
import asyncio
import time
from datetime import datetime
from dataclasses import dataclass, asdict
from typing import List, Optional
from pathlib import Path

try:
    import aiohttp
except ImportError:
    print("ERROR: aiohttp not installed. Install with: pip install aiohttp")
    sys.exit(1)

# Configuration
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
MINIMAX_MODEL_ID = "minimax/minimax-m2.5"
API_KEY = "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"

# Execution settings
BATCH_SIZE = 25  # 25 parallel requests per batch
REQUEST_TIMEOUT = 300  # 5 min per request
BATCH_TIMEOUT = 600  # 10 min per batch
INTER_BATCH_DELAY = 2  # 2 seconds between batches

# Output
OUTPUT_DIR = "/mnt/e/genesis-system/swarm-output/session22/minimax500"

# System prompt for all agents
SYSTEM_PROMPT = """You are an expert content strategist and marketing copywriter for Sunaiva,
an Australian AI company that builds Talking Website Widgets — voice AI assistants embedded
directly on trade business websites. Our target market is Australian tradies (plumbers,
electricians, HVAC technicians, builders, painters, roofers, landscapers, etc.).

Key facts:
- Product: AI Voice Widget that answers calls, books jobs, handles enquiries 24/7
- Pricing: Starter $197/mo, Pro $397/mo, Growth $597/mo (AUD)
- Agency commission: 30% recurring for web agency partners
- Cost per widget: ~$20/mo (Telnyx voice)
- Target: Australian trade businesses and the web agencies that serve them
- Brand voice: Practical, no-BS, results-focused. Speak like a tradie's mate, not a tech bro.
- Key value props: Never miss a call, book jobs while you're on the tools, 24/7 availability,
  costs less than a part-time receptionist

Be specific, practical, and include Australian context (suburbs, slang, real scenarios).
Write content that is ready to use — not generic templates. Make it feel real and human."""


@dataclass
class AgentResult:
    agent_id: int
    category: str
    category_num: int
    task_title: str
    status: str  # success/fail
    prompt_tokens: int
    completion_tokens: int
    total_tokens: int
    cost_usd: float
    response_time_ms: int
    response: Optional[str] = None
    error: Optional[str] = None
    timestamp: str = None

    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = datetime.now().isoformat()


def generate_stories() -> List[dict]:
    """Generate 500 stories across 10 categories (50 each)."""
    stories = []
    agent_id = 1

    # Category 1: Widget Customization Variations (50)
    industries = [
        "plumber", "electrician", "HVAC technician", "builder", "painter",
        "roofer", "landscaper", "carpet cleaner", "pest controller", "locksmith",
        "tiler", "concreter", "fencer", "glass repairer", "gutter cleaner",
        "handyman", "pool builder", "solar installer", "tree lopper", "welder",
        "bricklayer", "cabinet maker", "carpenter", "demolition contractor", "drainage specialist",
        "flooring installer", "garage door installer", "insulation contractor", "irrigation specialist", "kitchen renovator",
        "bathroom renovator", "marine mechanic", "mobile mechanic", "paver", "plasterer",
        "scaffolder", "septic tank specialist", "shed builder", "signwriter", "stonemasonry",
        "stump grinder", "tow truck operator", "waterproofer", "window cleaner", "excavator operator",
        "air conditioning installer", "antenna installer", "appliance repairer", "awning installer", "blinds installer"
    ]
    for industry in industries:
        stories.append({
            "agent_id": agent_id,
            "category": "widget_customization",
            "category_num": 1,
            "task_title": f"Widget design for {industry}",
            "prompt": f"""Design a complete widget customization specification for a {industry} business website.

Include:
1. **Color Scheme**: Primary, secondary, accent colors with hex codes (match typical {industry} branding)
2. **Widget Position**: Recommended placement (bottom-right, bottom-left, etc.) with reasoning
3. **Widget Size**: Desktop and mobile dimensions
4. **Avatar/Icon**: Describe the avatar icon that represents the AI assistant
5. **Welcome Message**: The first thing the widget says when opened (Australian English)
6. **Animations**: Entry animation, idle animation, notification pulse
7. **Typography**: Font family, sizes for header/body/caption
8. **Button Styles**: CTA button colors, hover states, border radius
9. **Dark Mode Variant**: How the widget looks in dark mode
10. **Industry-Specific Elements**: Any unique design elements for {industry} businesses

Output as a complete JSON configuration object ready to be consumed by a widget renderer.
Include CSS custom properties (variables) for easy theming."""
        })
        agent_id += 1

    # Category 2: FAQ Content for Different Trades (50)
    trades_faq = [
        ("plumber", "blocked drains, hot water systems, gas fitting, leak detection, bathroom renovations"),
        ("electrician", "safety switches, rewiring, LED upgrades, smoke alarms, EV charger installation"),
        ("HVAC technician", "split system installation, ducted AC, gas heating, AC servicing, refrigerant leaks"),
        ("builder", "home extensions, granny flats, knockdown rebuilds, council approvals, site preparation"),
        ("painter", "interior painting, exterior painting, spray painting, colour consulting, wallpaper removal"),
        ("roofer", "roof restoration, tile replacement, metal roofing, gutter replacement, roof leak repair"),
        ("landscaper", "garden design, retaining walls, artificial turf, irrigation, outdoor lighting"),
        ("carpet cleaner", "steam cleaning, stain removal, upholstery cleaning, tile and grout cleaning, flood restoration"),
        ("pest controller", "termite inspection, cockroach treatment, rodent control, spider treatment, ant control"),
        ("locksmith", "emergency lockout, lock replacement, master key systems, safe opening, security audit"),
        ("tiler", "bathroom tiling, kitchen splashbacks, outdoor tiling, waterproofing, tile repair"),
        ("concreter", "concrete driveways, exposed aggregate, concrete slabs, decorative concrete, concrete polishing"),
        ("fencer", "colorbond fencing, timber fencing, pool fencing, security fencing, gate automation"),
        ("glass repairer", "broken window repair, shower screens, splashbacks, double glazing, security glass"),
        ("gutter cleaner", "gutter cleaning, leaf guard installation, downpipe clearing, roof valley clearing, gutter repair"),
        ("handyman", "furniture assembly, door repairs, shelf installation, picture hanging, minor plumbing"),
        ("pool builder", "pool construction, pool renovation, pool heating, pool fencing, spa installation"),
        ("solar installer", "solar panel installation, battery storage, solar hot water, system monitoring, grid connection"),
        ("tree lopper", "tree removal, tree pruning, stump grinding, emergency tree work, palm cleaning"),
        ("welder", "structural welding, mobile welding, aluminium welding, stainless steel, custom fabrication"),
        ("bricklayer", "brick walls, retaining walls, brick repair, letterboxes, BBQ areas"),
        ("cabinet maker", "custom kitchens, wardrobes, bathroom vanities, entertainment units, office fitouts"),
        ("carpenter", "decking, pergolas, timber framing, door hanging, staircase construction"),
        ("demolition contractor", "house demolition, partial demolition, asbestos removal, site clearing, salvage"),
        ("drainage specialist", "stormwater drainage, blocked drains, drain relining, CCTV inspection, French drains"),
        ("flooring installer", "timber flooring, vinyl plank, laminate, carpet, epoxy flooring"),
        ("garage door installer", "roller doors, sectional doors, tilt doors, automatic openers, door repair"),
        ("insulation contractor", "ceiling insulation, wall insulation, underfloor insulation, soundproofing, thermal assessment"),
        ("irrigation specialist", "sprinkler systems, drip irrigation, smart controllers, bore pumps, system repair"),
        ("kitchen renovator", "full kitchen renovation, benchtop replacement, splashback installation, appliance fitting, design"),
        ("bathroom renovator", "full bathroom renovation, walk-in shower, bathtub installation, waterproofing, tiling"),
        ("mobile mechanic", "car servicing, brake repair, battery replacement, oil change, pre-purchase inspection"),
        ("paver", "driveway paving, patio paving, pool surround, natural stone, brick paving"),
        ("plasterer", "plastering walls, ceiling plastering, cornice installation, render repair, decorative plaster"),
        ("scaffolder", "residential scaffolding, commercial scaffolding, event scaffolding, scaffold hire, safety inspection"),
        ("septic tank specialist", "septic installation, septic pumping, septic repair, grease trap cleaning, treatment systems"),
        ("shed builder", "colorbond sheds, barn style, garage, workshop, custom designs"),
        ("signwriter", "shop signage, vehicle wraps, LED signs, banners, window graphics"),
        ("stonemason", "stone walls, stone cladding, stone benchtops, monument restoration, custom stonework"),
        ("stump grinder", "stump removal, root ball removal, site preparation, mulch supply, large stump specialist"),
        ("waterproofer", "bathroom waterproofing, balcony waterproofing, basement waterproofing, membrane application, leak repair"),
        ("window cleaner", "residential window cleaning, commercial window cleaning, high-rise, solar panel cleaning, screen cleaning"),
        ("excavator operator", "site excavation, pool excavation, trenching, land clearing, rock breaking"),
        ("air conditioning installer", "split system, multi-split, ducted, cassette, maintenance plans"),
        ("antenna installer", "TV antenna, satellite dish, signal booster, point-to-point, CCTV installation"),
        ("appliance repairer", "washing machine repair, fridge repair, dishwasher repair, oven repair, dryer repair"),
        ("awning installer", "folding arm, fixed frame, retractable, motorised, outdoor blinds"),
        ("blinds installer", "roller blinds, venetian, plantation shutters, vertical blinds, motorised blinds"),
        ("deck builder", "timber decking, composite decking, rooftop deck, pool deck, balcony"),
        ("fire protection specialist", "fire sprinklers, fire alarms, extinguisher servicing, passive fire, emergency lighting"),
    ]
    for trade, services in trades_faq:
        stories.append({
            "agent_id": agent_id,
            "category": "faq_content",
            "category_num": 2,
            "task_title": f"FAQ content for {trade}",
            "prompt": f"""Create a comprehensive FAQ database for a {trade}'s AI voice widget.
The widget needs to answer customer questions naturally via voice.

Services offered: {services}

Generate 20 FAQs in this exact JSON format:
```json
[
  {{
    "question": "How much does it cost to ...",
    "short_answer": "One sentence answer for quick voice response",
    "detailed_answer": "2-3 sentence detailed answer with specifics",
    "keywords": ["keyword1", "keyword2"],
    "category": "pricing|availability|process|warranty|emergency",
    "follow_up_question": "Would you like me to book a quote for that?"
  }}
]
```

Requirements:
- Australian English (use "enquiry" not "inquiry", "organisation" not "organization")
- Include realistic pricing ranges in AUD where applicable
- Cover: pricing, availability, process, warranties, emergency callouts
- Include at least 2 emergency/after-hours questions
- Include at least 2 pricing/quote questions
- Make answers conversational — these are SPOKEN by a voice AI, not read on screen
- Reference Australian standards/regulations where relevant"""
        })
        agent_id += 1

    # Category 3: Objection Handling Scripts (50)
    objections = [
        ("too expensive", "price-conscious tradie who thinks $197/mo is too much"),
        ("already have a receptionist", "tradie who employs a part-time receptionist"),
        ("don't trust AI", "old-school tradie who doesn't trust technology"),
        ("my clients are old school", "tradie who thinks their customers won't talk to AI"),
        ("I don't get many calls", "solo tradie who thinks they don't need it"),
        ("I'll just call them back", "tradie who thinks returning missed calls is fine"),
        ("my wife handles the phone", "tradie whose spouse answers the phone"),
        ("I use a call answering service", "tradie using a human answering service"),
        ("I'm too busy to set it up", "tradie who thinks setup is complicated"),
        ("what if it gets something wrong", "tradie worried about AI making mistakes"),
        ("I need to think about it", "classic stall tactic from an interested tradie"),
        ("can I try it for free", "tradie who wants a free trial before committing"),
        ("my mate tried AI and it was rubbish", "tradie influenced by someone else's bad experience"),
        ("I just use Google to get leads", "tradie who relies only on Google Ads/SEO"),
        ("my customers prefer texting", "tradie who thinks voice is outdated"),
        ("I don't have a website", "tradie without an existing website"),
        ("it won't understand trade terms", "tradie worried about industry jargon"),
        ("what about my existing phone number", "tradie who doesn't want to change their number"),
        ("I'm seasonal — too quiet in winter", "tradie with seasonal work patterns"),
        ("I tried chatbots and they're terrible", "tradie who had bad chatbot experiences"),
        ("how is this different from Siri", "tradie comparing to consumer AI assistants"),
        ("my accountant won't approve another expense", "tradie constrained by accounting/budget"),
        ("I only want it for after hours", "tradie who only wants evening/weekend coverage"),
        ("what happens when I cancel", "tradie worried about lock-in or data loss"),
        ("I don't want customers knowing it's AI", "tradie worried about perception"),
        ("it's just a gimmick", "dismissive tradie who doesn't see the value"),
        ("I've got an apprentice who answers phones", "tradie using apprentice as receptionist"),
        ("we use a booking app already", "tradie using ServiceM8, Tradify, or similar"),
        ("my Google Business profile gets me enough work", "tradie relying on GBP"),
        ("I'm a one-man band, I don't need this", "solo operator who thinks it's for bigger businesses"),
        ("the technology will be outdated in 6 months", "tradie worried about rapid tech change"),
        ("I don't understand how it works", "tradie who needs simple explanation"),
        ("what about privacy and data", "privacy-conscious tradie"),
        ("I need to talk to my business partner", "decision involves another person"),
        ("send me some info and I'll look at it later", "brush-off tactic"),
        ("do you have references from tradies in my area", "social proof seeker"),
        ("I just renewed my phone contract", "tradie who thinks it involves phone hardware"),
        ("my customers need to talk to a real person", "perception that AI can't handle nuanced queries"),
        ("I'm retiring in a few years", "older tradie near retirement"),
        ("my son handles all the tech stuff", "older tradie deferring to family"),
        ("how do I know you won't steal my customer data", "trust and data ownership concern"),
        ("I had my identity stolen, I'm careful with online stuff", "cautious after bad experience"),
        ("can it speak another language", "tradie with multilingual customer base"),
        ("what if the internet goes down", "reliability concern"),
        ("I don't have good phone signal on job sites", "connectivity concern"),
        ("this sounds like something for corporate, not tradies", "thinking it's enterprise-only"),
        ("I'd rather spend the money on Google Ads", "marketing budget allocation"),
        ("how long before I see results", "ROI timeline expectation"),
        ("what if I get too many leads and can't handle them", "capacity concern — actually positive"),
        ("I'll wait until the slow season to try it", "procrastination disguised as planning"),
    ]
    for objection, persona in objections:
        stories.append({
            "agent_id": agent_id,
            "category": "objection_handling",
            "category_num": 3,
            "task_title": f"Objection: {objection}",
            "prompt": f"""Write a comprehensive objection handling script for this scenario:

**Objection:** "{objection}"
**Persona:** {persona}

Create a complete response framework:

1. **Acknowledge** (1-2 sentences): Validate their concern without being dismissive
2. **Reframe** (2-3 sentences): Shift the perspective to show the real cost of NOT having the widget
3. **Evidence** (2-3 sentences): Provide a specific, believable example or stat
4. **Close** (1-2 sentences): Direct call to action

Also provide:
- **One-liner response** (for quick SMS/email follow-up)
- **3 follow-up questions** to keep the conversation going
- **Math breakdown** showing ROI (use realistic Australian tradie numbers — avg job $350-1,500)
- **Tone notes** for the salesperson (what to avoid, what to emphasize)

Write in Australian English. Be direct, no-BS. Think of how one tradie would convince another tradie mate at the pub."""
        })
        agent_id += 1

    # Category 4: Industry-Specific Widget Prompts (50)
    prompt_industries = [
        ("plumber", "24/7 emergency plumbing, hot water, blocked drains, gas fitting, bathroom renos"),
        ("electrician", "residential electrical, commercial, emergency, solar, EV chargers"),
        ("HVAC tech", "air conditioning install/service, heating, ventilation, refrigeration"),
        ("general builder", "home extensions, renovations, new builds, granny flats"),
        ("house painter", "interior, exterior, commercial painting, colour consulting"),
        ("roofer", "roof restoration, repairs, new roofing, gutters, fascia"),
        ("landscaper", "garden design, hardscaping, retaining walls, irrigation, maintenance"),
        ("carpet cleaner", "residential, commercial, stain removal, upholstery, flood restoration"),
        ("pest controller", "termites, general pest, rodents, commercial pest, pre-purchase inspections"),
        ("locksmith", "emergency lockout, rekey, master key, commercial security, safe services"),
        ("tiler", "bathroom, kitchen, floor, outdoor, waterproofing"),
        ("concreter", "driveways, slabs, paths, decorative concrete, exposed aggregate"),
        ("fencer", "colorbond, timber, pool, security, automatic gates"),
        ("pool builder", "concrete pools, fibreglass, renovation, heating, maintenance"),
        ("solar installer", "residential solar, commercial, battery storage, monitoring"),
        ("tree service", "removal, pruning, stump grinding, emergency, palm cleaning"),
        ("demolition", "house demo, partial, asbestos removal, site clearing"),
        ("flooring installer", "timber, vinyl, laminate, carpet, epoxy"),
        ("garage door specialist", "installation, repair, automation, commercial doors"),
        ("kitchen renovator", "full renos, benchtops, splashbacks, custom cabinetry"),
        ("bathroom renovator", "complete renos, waterproofing, accessibility modifications"),
        ("mobile mechanic", "servicing, repairs, diagnostics, pre-purchase, fleet"),
        ("excavation operator", "site prep, trenching, pool dig, land clearing, rock breaking"),
        ("scaffolder", "residential, commercial, event, hire, safety certification"),
        ("waterproofer", "bathroom, balcony, basement, deck, remedial"),
        ("window cleaner", "residential, commercial, high-rise, solar panels, screens"),
        ("appliance repairer", "white goods, ovens, dishwashers, fridges, warranties"),
        ("antenna installer", "TV, satellite, internet, CCTV, intercom"),
        ("fire protection", "sprinklers, alarms, extinguishers, compliance, emergency lighting"),
        ("shed builder", "residential sheds, barns, garages, workshops, farm buildings"),
        ("signwriter", "shop fronts, vehicles, LED, banners, window graphics"),
        ("stonemason", "walls, benchtops, cladding, restoration, custom work"),
        ("deck builder", "timber, composite, rooftop, balcony, maintenance"),
        ("insulation installer", "ceiling, wall, underfloor, soundproofing, assessment"),
        ("irrigation specialist", "sprinklers, drip, smart systems, bore pumps, repair"),
        ("septic specialist", "installation, pumping, repair, grease traps, compliance"),
        ("glass specialist", "windows, shower screens, splashbacks, mirrors, security glass"),
        ("gutter specialist", "cleaning, replacement, leaf guard, downpipes, repairs"),
        ("cabinet maker", "kitchens, wardrobes, vanities, entertainment units, office"),
        ("plasterer", "walls, ceilings, cornices, rendering, decorative"),
        ("paver", "driveways, patios, pool surrounds, paths, retaining walls"),
        ("welder", "structural, mobile, aluminium, stainless, custom fab"),
        ("bricklayer", "walls, retaining, repairs, features, commercial"),
        ("stump grinder", "stump removal, root ball, land clearing, mulch"),
        ("air con installer", "split system, ducted, multi-split, cassette, maintenance"),
        ("awning installer", "folding arm, fixed, retractable, motorised, shade sails"),
        ("blinds installer", "roller, venetian, shutters, vertical, motorised"),
        ("cleaning service", "commercial, residential, end-of-lease, window, carpet"),
        ("security installer", "CCTV, alarms, access control, intercom, monitoring"),
        ("earthmoving contractor", "excavation, grading, site prep, drainage, dam construction"),
    ]
    for trade, services in prompt_industries:
        stories.append({
            "agent_id": agent_id,
            "category": "widget_prompts",
            "category_num": 4,
            "task_title": f"System prompt for {trade}",
            "prompt": f"""Write a complete system prompt for an AI voice assistant widget on a {trade}'s website.

Services: {services}

The system prompt must include:

1. **Identity & Persona**: Who the AI is (name, role, personality)
2. **Business Context**: What the business does, service area, hours
3. **Greeting Script**: Exactly what to say when a visitor opens the widget
4. **Service Knowledge**: Key info about each service offered
5. **Booking Logic**: How to collect info for a quote/booking (name, phone, address, job description, urgency)
6. **Pricing Guidelines**: What to say about pricing (never give exact quotes, offer free on-site quotes)
7. **Emergency Handling**: How to prioritize emergency vs standard enquiries
8. **Handoff Rules**: When to transfer to a human (complex jobs, complaints, existing customers)
9. **Upsell Opportunities**: Natural ways to mention additional services
10. **Closing Script**: How to end conversations positively

Format as a ready-to-paste system prompt (not a template — a REAL prompt with placeholder {{business_name}} and {{phone_number}} only).
Must be in Australian English. Tone: friendly, professional, efficient. Think "helpful receptionist at a busy trade business."
Include handling for: after-hours calls, repeat customers, urgent jobs, price shoppers, and tyre-kickers."""
        })
        agent_id += 1

    # Category 5: SEO Blog Post Content (50)
    blog_topics = [
        "Why Every Tradie Needs an AI Receptionist in 2026",
        "AI vs Human Receptionist: The Real Cost Comparison for Tradies",
        "How AI Saves Tradies $47,000 a Year in Missed Calls",
        "The Ultimate Guide to Never Missing a Customer Call Again",
        "5 Tradies Who Doubled Their Revenue with AI Voice Assistants",
        "Why Your Competitor Is Booking Jobs While You're on the Tools",
        "The Hidden Cost of Missed Calls for Australian Trade Businesses",
        "How a Plumber in Sydney Added $120K Revenue with AI",
        "AI Voice Assistants: Everything Australian Tradies Need to Know",
        "From Missed Call to Booked Job in 30 Seconds: The AI Advantage",
        "Why Smart Tradies Are Ditching Call Answering Services for AI",
        "The Tradie's Guide to Automating Customer Enquiries",
        "How AI Handles Emergency Plumbing Calls Better Than Voicemail",
        "10 Things Your AI Receptionist Can Do That You Didn't Know About",
        "The ROI of AI: Breaking Down the Numbers for Trade Businesses",
        "How to Choose the Right AI Voice Assistant for Your Trade Business",
        "AI Receptionist vs Chatbot: What's the Difference and Why It Matters",
        "Why Voicemail Is Killing Your Trade Business (And What to Do Instead)",
        "The Future of Customer Service in the Australian Trades Industry",
        "How Website Widgets Are Replacing Phone Trees for Tradies",
        "After-Hours Gold: How AI Captures Jobs While You Sleep",
        "How Electricians Use AI to Handle Safety Switch Emergency Calls",
        "The Builder's Guide to AI-Powered Lead Qualification",
        "Why Tradies' Wives Are the Biggest Fans of AI Receptionists",
        "How to Set Up an AI Voice Widget on Your Trade Website in 10 Minutes",
        "The Psychology of Why Customers Prefer Talking to AI After Hours",
        "How AI Voice Assistants Handle Angry Customers for Tradies",
        "From Sole Trader to Smart Trader: AI Tools That Scale Your Business",
        "How Landscapers Use AI to Book More Spring Projects",
        "The Complete Guide to AI Customer Service for HVAC Businesses",
        "Why Google Reviews Improve When You Stop Missing Calls",
        "How AI Helps Tradies Win More Emergency Call-Out Jobs",
        "The Tradie Tech Stack: 5 AI Tools Every Trade Business Needs",
        "How to Train Your AI Assistant to Sound Like Your Best Employee",
        "Why AI Voice Beats Text Chat for Trade Business Websites",
        "How Pool Builders Use AI to Convert Website Visitors into Quotes",
        "The Environmental Case for AI Receptionists (Less Paper, Less Waste)",
        "How to Use AI to Upsell Additional Services Without Being Pushy",
        "The Definitive Guide to AI Voice for Australian Small Businesses",
        "How Roofing Companies Use AI to Handle Storm Damage Enquiry Surges",
        "AI for Tradies: Separating Fact from Fiction",
        "How AI Receptionists Help Tradies Get Better Work-Life Balance",
        "The Cost of a Missed Call: Real Data from Australian Trade Businesses",
        "How to Get Your Tradie Mates to Try AI (Without the Eye-Roll)",
        "Why Regional Tradies Benefit Most from AI Voice Technology",
        "How AI Handles Multiple Calls Simultaneously for Busy Tradies",
        "The Ultimate FAQ: Everything Tradies Ask About AI Voice Widgets",
        "How Pest Control Companies Use AI During Termite Season",
        "AI Voice Assistants: The Unfair Advantage Smart Tradies Don't Talk About",
        "Why 2026 Is the Year Every Trade Business Gets an AI Receptionist",
    ]
    for topic in blog_topics:
        stories.append({
            "agent_id": agent_id,
            "category": "seo_blog_content",
            "category_num": 5,
            "task_title": f"Blog: {topic[:50]}...",
            "prompt": f"""Write a complete SEO-optimized blog post for the Sunaiva website.

**Title:** {topic}

Requirements:
1. **Length**: 800-1,200 words
2. **SEO**: Include target keyword naturally 3-5 times, use H2/H3 headings, include meta description
3. **Tone**: Conversational Australian English, written for tradies not tech people
4. **Structure**:
   - Hook paragraph (grab attention with a relatable tradie scenario)
   - Problem section (paint the pain of current situation)
   - Solution section (introduce AI voice widget)
   - Social proof (include a realistic-sounding case study or stat)
   - FAQ section (3 common questions with answers)
   - CTA (clear call to action)
5. **Meta Description**: 155 characters max
6. **Suggested URL Slug**: kebab-case
7. **Internal Links**: Suggest 2-3 internal link opportunities
8. **Schema Markup**: Suggest FAQ schema for the FAQ section

Write the COMPLETE blog post, not an outline. Make it publish-ready."""
        })
        agent_id += 1

    # Category 6: Social Media Posts (50)
    social_types = [
        ("LinkedIn", "professional insight post about AI transforming trades industry"),
        ("LinkedIn", "case study format: before/after of a tradie using AI receptionist"),
        ("LinkedIn", "thought leadership: why the $40B Australian trades industry needs AI"),
        ("LinkedIn", "data-driven post: cost of missed calls with infographic concept"),
        ("LinkedIn", "personal story format: meeting a tradie who lost $50K to missed calls"),
        ("LinkedIn", "contrarian take: why AI receptionists are BETTER than human ones"),
        ("LinkedIn", "carousel post concept: 7 signs you need an AI receptionist"),
        ("LinkedIn", "poll post: how many calls does your trade business miss per week"),
        ("LinkedIn", "celebration post: launching AI voice widgets for Australian tradies"),
        ("LinkedIn", "educational post: how AI voice technology actually works (simplified)"),
        ("Facebook", "pain-point post targeting plumber business owners"),
        ("Facebook", "before/after transformation for electrician business"),
        ("Facebook", "humorous post about tradies missing calls while on the tools"),
        ("Facebook", "testimonial-style post from a fictional happy tradie customer"),
        ("Facebook", "video script: 60-second demo of AI answering a plumber's phone"),
        ("Facebook", "comparison post: AI receptionist vs voicemail vs answering service"),
        ("Facebook", "seasonal post: why summer is when tradies miss the most calls"),
        ("Facebook", "community engagement: poll about biggest business challenges for tradies"),
        ("Facebook", "offer post: limited beta pricing for first 50 tradies"),
        ("Facebook", "educational carousel: what happens when a customer calls and you don't answer"),
        ("Facebook", "story ad: tradie Steve was losing $1,000/week in missed calls"),
        ("Facebook", "retargeting ad: still missing calls? Here's what it's costing you"),
        ("Facebook", "lookalike audience ad: AI receptionist built specifically for Aussie tradies"),
        ("Facebook", "event promo: free webinar on AI for trade businesses"),
        ("Facebook", "group post for tradie Facebook groups: who else misses calls on the tools"),
        ("Instagram", "reel script: day in the life of a tradie's AI receptionist"),
        ("Instagram", "carousel: 5 calls your AI answers while you're under a house"),
        ("Instagram", "story sequence: setting up your AI widget in real-time"),
        ("Instagram", "reel script: the face tradies make when they see their missed call log"),
        ("Instagram", "infographic: anatomy of a perfectly handled customer call"),
        ("Instagram", "before/after: tradie's phone log without AI vs with AI"),
        ("Instagram", "meme format: when the AI books 3 jobs while you're at smoko"),
        ("Instagram", "carousel: real conversations between AI and customers (mockups)"),
        ("Instagram", "reel script: POV you're a tradie and AI just booked you a $2,000 job"),
        ("Instagram", "story poll: would you trust AI to answer your business calls"),
        ("Instagram", "carousel: pricing comparison AI vs receptionist vs answering service"),
        ("Instagram", "reel: tradie reaction to seeing AI handle a call perfectly"),
        ("Instagram", "infographic: how much does a missed call actually cost"),
        ("Instagram", "carousel: top 5 questions customers ask your AI (with real answers)"),
        ("Instagram", "reel script: interviewing the AI - can you really handle a plumbing enquiry"),
        ("LinkedIn", "agency pitch: why web agencies should offer AI voice widgets to tradie clients"),
        ("LinkedIn", "industry analysis: Australian trades industry technology adoption 2026"),
        ("LinkedIn", "how-to: building an AI voice agent for your trade business"),
        ("LinkedIn", "partnership announcement: opening our agency partner program"),
        ("LinkedIn", "behind-the-scenes: how we built AI that understands Australian trade slang"),
        ("Facebook", "customer win: AI booked 12 jobs in one weekend for a roofer"),
        ("Facebook", "myth-busting: 5 things tradies get wrong about AI"),
        ("Facebook", "seasonal: pre-winter HVAC rush — is your phone ready"),
        ("Instagram", "reel: what customers actually say to our AI (surprising conversations)"),
        ("Instagram", "carousel: the silent killer of trade businesses — missed calls stats"),
    ]
    for platform, post_type in social_types:
        stories.append({
            "agent_id": agent_id,
            "category": "social_media",
            "category_num": 6,
            "task_title": f"{platform}: {post_type[:40]}...",
            "prompt": f"""Write a complete {platform} post for Sunaiva's social media.

**Platform:** {platform}
**Post Type:** {post_type}

Include:
1. **Full Post Copy**: Ready to publish, with appropriate length for {platform}
2. **Hashtags**: 5-10 relevant hashtags (mix of broad and niche)
3. **Visual Direction**: Describe the image/video/carousel slides needed
4. **CTA**: Clear call to action
5. **Best Time to Post**: Recommended posting time for Australian audience
6. **Engagement Hook**: First line must stop the scroll
7. **Comment Strategy**: 3 sample replies to likely comments

Platform-specific requirements:
- LinkedIn: Professional but relatable, 1,300 chars max for organic reach, use line breaks
- Facebook: Conversational, use emojis sparingly, optimise for shares
- Instagram: Visual-first, caption under 2,200 chars, strong first line, CTA in bio

Target audience: Australian trade business owners (25-55 years old, male-dominated, practical-minded).
Write in Australian English. No corporate jargon. Sound like a mate who happens to know about AI."""
        })
        agent_id += 1

    # Category 7: Email Subject Line A/B Variants (50)
    email_contexts = [
        "cold outreach to plumber who doesn't know about AI",
        "cold outreach to electrician business owner",
        "cold outreach to HVAC company with 5+ employees",
        "cold outreach to general builder running a team",
        "follow-up after no reply to first email",
        "follow-up after website visit (retargeting)",
        "follow-up after demo request but no-show",
        "beta invitation for early adopters",
        "limited time offer — 50% off first 3 months",
        "seasonal angle — summer rush preparation",
        "seasonal angle — winter slowdown productivity",
        "pain point — missed calls costing money",
        "pain point — working evenings returning calls",
        "pain point — losing jobs to faster competitors",
        "social proof — other tradies in their area using it",
        "curiosity gap — surprising stat about missed calls",
        "direct benefit — book more jobs without extra staff",
        "fear of missing out — competitors already using AI",
        "authority — featured in trade magazine / podcast",
        "personal — from one small business owner to another",
        "question format — are you still missing calls",
        "news angle — new AI technology for Australian tradies",
        "referral — [Name] suggested I reach out",
        "comparison — AI vs your current solution",
        "ROI focused — how to add $X revenue per month",
        "time-saving angle — get your evenings back",
        "agency partner recruitment email",
        "web developer partnership opportunity",
        "reactivation — haven't heard from you in 30 days",
        "case study share — how Dave the plumber added $8K/mo",
        "free resource — guide to never missing calls",
        "webinar invitation — live demo of AI for tradies",
        "event-based — trade show follow-up",
        "milestone — 100th tradie customer celebration",
        "product update — new feature announcement",
        "holiday — Christmas/New Year special offer",
        "local angle — AI for [City] tradies specifically",
        "video — 60-second demo inside",
        "challenge — try AI free for 7 days challenge",
        "urgency — only 10 beta spots remaining",
        "gratitude — thank you for considering Sunaiva",
        "educational — 3 things killing your lead conversion",
        "provocative — your voicemail is losing you $500/week",
        "storytelling — how a Penrith plumber changed his business",
        "benefit stack — 24/7 calls + booking + follow-up in one widget",
        "industry report — 2026 AI adoption in Australian trades",
        "cold outreach to web agency about partner program",
        "cold outreach to trade association about member benefit",
        "re-engagement after trial expired",
        "win-back — we've improved since you last checked",
    ]
    for context in email_contexts:
        stories.append({
            "agent_id": agent_id,
            "category": "email_subjects",
            "category_num": 7,
            "task_title": f"Email subjects: {context[:40]}...",
            "prompt": f"""Generate 10 email subject line variants for A/B testing.

**Context:** {context}

For each subject line, provide:
1. **Subject Line**: The actual subject (under 50 characters ideal, max 60)
2. **Preview Text**: First line of email body that shows in inbox (under 90 chars)
3. **Psychological Trigger**: Which trigger it uses (curiosity, fear, social proof, urgency, benefit, question, personalization, news)
4. **Expected Open Rate**: Estimate (low/medium/high) with reasoning
5. **Best For**: Which segment this works best for (cold/warm/hot)

Also provide:
- **Winning Prediction**: Which of the 10 you'd bet on and why
- **Spam Trigger Warning**: Flag any that might trigger spam filters
- **Mobile Preview**: How the subject looks truncated on mobile (35 chars)

Requirements:
- Australian English and context
- No ALL CAPS (spam trigger)
- No excessive punctuation
- Personalisation tokens where appropriate: {{first_name}}, {{business_name}}, {{suburb}}
- At least 3 should be under 40 characters (mobile-optimised)
- Mix of approaches: question, statement, number, curiosity gap, benefit-led"""
        })
        agent_id += 1

    # Category 8: Partner Pitch Scripts (50)
    partner_types = [
        ("small web agency", "5-20 tradie clients, 2-5 employees, builds WordPress sites"),
        ("mid-size digital agency", "20-50 clients mixed industries, offers SEO/PPC/web"),
        ("freelance web developer", "solo, builds 3-5 sites per month, mostly trades"),
        ("SEO agency", "focuses on local SEO for tradies, 30+ clients"),
        ("marketing agency", "full-service marketing for small businesses"),
        ("GHL/HighLevel agency", "runs automation and funnels on GoHighLevel"),
        ("social media manager", "manages Facebook/Instagram for trade businesses"),
        ("IT service provider", "provides tech support to small businesses"),
        ("business coach", "coaches tradies on business growth and systems"),
        ("accountant serving tradies", "has 50+ tradie clients, trusted advisor"),
        ("trade association", "represents 500+ members in a specific trade"),
        ("print/signage company", "provides vehicle wraps and signage to tradies"),
        ("trade magazine/publication", "reaches 10,000+ tradie subscribers"),
        ("Google Ads specialist", "manages PPC campaigns for trade businesses"),
        ("CRM provider", "sells ServiceM8, Tradify, or similar to tradies"),
        ("phone system provider", "sells VoIP/phone systems to small businesses"),
        ("website hosting company", "hosts websites for Australian small businesses"),
        ("business networking group", "BNI or similar group with tradie members"),
        ("trade school/TAFE", "trains apprentices and emerging tradies"),
        ("insurance broker", "provides trade insurance to hundreds of businesses"),
        ("franchise network", "supports franchised trade businesses"),
        ("commercial real estate agent", "helps tradies find warehouse/office space"),
        ("vehicle fleet manager", "manages vehicle fleets for trade companies"),
        ("uniform/workwear supplier", "sells to hundreds of trade businesses"),
        ("tool/equipment supplier", "large customer base of trade professionals"),
        ("Shopify agency", "builds ecommerce sites, looking to expand into services"),
        ("WordPress theme developer", "creates themes specifically for trade businesses"),
        ("podcast host", "runs a podcast for trade business owners"),
        ("YouTube content creator", "creates how-to and business content for tradies"),
        ("Xero/MYOB accountant", "specialises in cloud accounting for trades"),
        ("HR consultant for trades", "helps trade businesses with hiring and compliance"),
        ("safety/compliance consultant", "provides WHS consulting to trade businesses"),
        ("finance broker", "arranges vehicle and equipment finance for tradies"),
        ("commercial cleaning company", "runs cleaning crews, understands service business model"),
        ("property management company", "manages properties, uses tradies for maintenance"),
        ("real estate agency", "refers tradies for pre-sale renovations"),
        ("strata management", "manages strata buildings, coordinates tradie work"),
        ("local council business support", "runs small business programs"),
        ("startup incubator", "supports tech-adjacent small businesses"),
        ("white-label SaaS reseller", "resells software solutions to SMBs"),
        ("Squarespace developer", "builds modern websites for service businesses"),
        ("Wix agency partner", "specialises in Wix websites for local businesses"),
        ("graphic designer serving tradies", "does logos, business cards, wraps"),
        ("email marketing agency", "runs email campaigns for B2B clients"),
        ("customer review platform", "helps businesses collect Google reviews"),
        ("payment processing company", "provides EFTPOS/payment solutions"),
        ("virtual assistant service", "provides remote admin support to tradies"),
        ("co-working space", "houses many solo tradies and small businesses"),
        ("industry event organiser", "runs trade shows and expos"),
        ("recruitment agency", "places tradies and apprentices"),
    ]
    for partner, description in partner_types:
        stories.append({
            "agent_id": agent_id,
            "category": "partner_pitches",
            "category_num": 8,
            "task_title": f"Partner pitch: {partner}",
            "prompt": f"""Write a complete partner pitch script for approaching a {partner}.

**Partner Description:** {description}

Create a full sales playbook:

1. **Research Checklist**: What to find out about this partner before reaching out
2. **Cold Email**: Complete email to initiate the conversation (under 150 words)
3. **LinkedIn Message**: DM version (under 300 characters)
4. **Phone Script**: If they pick up, what to say in the first 30 seconds
5. **Value Proposition**: Specific to THIS type of partner:
   - What's in it for them (30% recurring commission)
   - How it makes their existing offering stronger
   - Why their clients will love it
6. **Objection Handling**: 3 likely objections from THIS partner type and responses
7. **Commission Calculator**: Show them their potential monthly revenue
   - Example: 20 clients x $197/mo widget x 30% = $1,182/mo passive income
8. **Onboarding Offer**: What you'll do for them to get started (free setup, demo, training)
9. **Follow-Up Sequence**: 3-touch follow-up plan with timing and content
10. **Partnership Tier**: Suggest which partner tier fits (Referral/Reseller/White-Label)

Write in Australian English. Be professional but approachable.
Remember: you're offering them REVENUE, not asking for a favour."""
        })
        agent_id += 1

    # Category 9: Customer Success Story Templates (50)
    success_stories = [
        ("Dave the Plumber", "Sydney", "solo operator, was missing 60% of calls while under houses"),
        ("Sarah's Electrical", "Melbourne", "3-person team, wife was overwhelmed answering phones"),
        ("Mike's HVAC Services", "Brisbane", "seasonal business, needed 24/7 coverage in summer"),
        ("BuildRight Construction", "Perth", "growing team of 8, needed professional phone presence"),
        ("Fresh Coat Painting", "Adelaide", "husband-wife team, painting all day, no time for calls"),
        ("TopNotch Roofing", "Gold Coast", "storm damage created call surges they couldn't handle"),
        ("Green Thumb Landscapes", "Newcastle", "booked solid but still losing leads on weekends"),
        ("ProClean Carpets", "Canberra", "mobile business, driving between jobs, missing every call"),
        ("BugBusters Pest Control", "Hobart", "termite season overwhelmed their single phone line"),
        ("KeyMaster Locksmiths", "Darwin", "emergency service, needed instant response capability"),
        ("TileArt by Marco", "Wollongong", "one-man band, lost a $15K bathroom job to voicemail"),
        ("SolidBase Concreting", "Geelong", "3 crews running, office phone constantly ringing"),
        ("SecureFence Solutions", "Townsville", "cyclone season prep created massive demand spike"),
        ("Crystal Clear Pools", "Sunshine Coast", "pool season means 50+ calls a day for 3 months"),
        ("SunPower Solar", "Cairns", "government rebate announcement caused call explosion"),
        ("TreeTop Services", "Ballarat", "storm aftermath, 200+ calls in one day, captured 90%"),
        ("Timberline Flooring", "Bendigo", "trade show generated 80 leads, AI followed up all of them"),
        ("AutoDoor Solutions", "Toowoomba", "commercial clients expect 24/7 response, now they get it"),
        ("DreamKitchens Reno", "Launceston", "high-value jobs ($30-80K), couldn't afford to miss one lead"),
        ("AquaFlow Drainage", "Mildura", "emergency drain services, response time is everything"),
        ("Jake's Mobile Mechanic", "Albury-Wodonga", "literally can't answer phone while under a car"),
        ("PeakPerformance HVAC", "Orange", "managing 15 techs, dispatch was a nightmare"),
        ("AllSafe Scaffolding", "Dubbo", "safety-critical business, needed documented call records"),
        ("AquaSeal Waterproofing", "Mandurah", "niche service, every lead is gold, was losing 40%"),
        ("SparkleClean Windows", "Rockhampton", "high-rise work means phone stays in the van"),
        ("PowerDig Excavation", "Wagga Wagga", "noisy worksites, literally can't hear the phone ring"),
        ("Elite Appliance Repair", "Bunbury", "warranty work requires specific info collection"),
        ("SignCraft Studios", "Tamworth", "creative work requires focus, interruptions kill productivity"),
        ("HeatWave Air Con", "Mackay", "summer peak: 3x normal call volume for 3 months"),
        ("TimberDeck Creations", "Port Macquarie", "seasonal business, needed consistent lead capture year-round"),
        ("SmartHome Installs", "Hervey Bay", "tech-savvy customers expect instant responses"),
        ("RapidResponse Electrical", "Shepparton", "24/7 emergency service, was relying on personal mobile"),
        ("MetalWorks Custom Fab", "Gladstone", "industrial clients, complex enquiry qualification needed"),
        ("EcoInsulate Solutions", "Cessnock", "government rebate program drove 5x normal enquiries"),
        ("FlowRight Irrigation", "Griffith", "farming clients call at 5am, needed early coverage"),
        ("CleanSweep Gutters", "Lismore", "flood aftermath, needed to handle compassionate enquiries"),
        ("CraftCabinets by Tom", "Bathurst", "high-end custom work, lead qualification is critical"),
        ("RenderPro Plastering", "Geraldton", "FIFO workers calling from remote sites at odd hours"),
        ("StoneMaster Masonry", "Armidale", "heritage restoration work, specialised enquiry handling"),
        ("LawnKing Maintenance", "Warrnambool", "100+ regular clients, needed booking management help"),
        ("DigDeep Stump Grinding", "Mount Gambier", "seasonal peaks after council tree removal programs"),
        ("ShadeRight Awnings", "Busselton", "summer rush, needed to capture leads during peak"),
        ("VisionBlinds Install", "Albany", "show-home referrals needed immediate response"),
        ("SprayTech Painting", "Kalgoorlie", "mining town, shift workers call at all hours"),
        ("WeldPro Engineering", "Broken Hill", "remote area, reliability is non-negotiable"),
        ("BrickWork Masters", "Devonport", "heritage brick restoration, niche with high-value leads"),
        ("TurfPro Landscapes", "Maitland", "new housing estates generating 30+ calls per week"),
        ("DrainTech Solutions", "Nowra", "blocked drain emergencies need instant response"),
        ("ShedMaster Builds", "Roma", "rural customers, long conversations need patient handling"),
        ("SafeGuard Fire Systems", "Gladstone", "compliance deadlines drive urgent booking requests"),
    ]
    for name, location, scenario in success_stories:
        stories.append({
            "agent_id": agent_id,
            "category": "success_stories",
            "category_num": 9,
            "task_title": f"Case study: {name} ({location})",
            "prompt": f"""Write a complete customer success story / case study.

**Business:** {name}
**Location:** {location}, Australia
**Scenario:** {scenario}

Create a publish-ready case study with:

1. **Headline**: Attention-grabbing result-focused headline
2. **Snapshot Box**:
   - Business: {name}
   - Location: {location}
   - Trade: [infer from name]
   - Challenge: [1 sentence]
   - Solution: Sunaiva AI Voice Widget
   - Result: [key metric improvement]
3. **The Challenge** (150 words): Paint the pain vividly. Use first-person quotes.
4. **Why Sunaiva** (100 words): What made them choose the AI widget
5. **The Results** (200 words): Specific, measurable outcomes with numbers:
   - Calls captured before vs after (e.g., 40% → 95%)
   - Revenue impact (calculate based on avg job value for their trade)
   - Time saved per week
   - Customer satisfaction improvement
6. **Quote**: A powerful testimonial quote from the business owner
7. **By The Numbers**: 3-4 key stats in a visual-friendly format
8. **What's Next**: How they plan to grow with Sunaiva
9. **CTA**: "Ready to see these results in your business?"

Make it BELIEVABLE. Use realistic numbers, Australian suburb names, trade-specific details.
This should read like a real customer story, not a marketing fairy tale."""
        })
        agent_id += 1

    # Category 10: Competitive Comparison Content (50)
    competitors = [
        ("Smith.ai", "US-based virtual receptionist service, human operators, $240-$900/mo"),
        ("Ruby Receptionists", "US live answering service, starts at $235/mo, human-powered"),
        ("AnswerConnect", "24/7 live answering, $325-$475/mo, human operators"),
        ("Moneypenny", "UK-based PA and receptionist service, premium pricing"),
        ("Abby Connect", "US boutique receptionist service, $329-$1,199/mo"),
        ("Nexa (formerly Answer1)", "US virtual receptionist, $200+/mo, bilingual"),
        ("PATLive", "US answering service, $205-$835/mo, 24/7 coverage"),
        ("Conversational", "Australian-based answering service, ~$50-200/mo"),
        ("Alltel", "Australian virtual receptionist, pay-per-call model"),
        ("OfficeHQ", "Australian answering service, from $20/mo + per call"),
        ("Intercom chatbot", "website chat widget, no voice, $74+/mo"),
        ("Drift chatbot", "conversational marketing platform, $2,500+/mo enterprise"),
        ("Tidio chatbot", "AI chatbot for websites, $29-$394/mo"),
        ("LiveChat", "website live chat software, $20-$59/mo per agent"),
        ("Zendesk chat", "customer service platform with chat, $55+/mo per agent"),
        ("Freshdesk chatbot", "customer support chatbot, $15-$79/mo per agent"),
        ("HubSpot chatbot", "free chatbot builder, limited features"),
        ("ManyChat", "Facebook/Instagram chatbot, $15+/mo"),
        ("Voiceflow", "voice AI builder platform, complex setup required"),
        ("Dialogflow", "Google's conversational AI, requires developer"),
        ("Vapi.ai", "voice AI platform, usage-based pricing, developer-focused"),
        ("Bland.ai", "AI phone calls, $0.09/min, developer API"),
        ("Retell AI", "voice agent builder, $0.07/min, requires coding"),
        ("Air AI", "autonomous AI phone agent, enterprise pricing"),
        ("Synthflow", "AI voice agent builder, $29-$450/mo"),
        ("Goodcall", "AI phone agent for SMBs, $59/mo starter"),
        ("Rosie AI", "AI answering service for home services, $49-$149/mo"),
        ("MissCall", "missed call text-back service, $97/mo"),
        ("CallHippo", "virtual phone system, $16-$40/mo per user"),
        ("Grasshopper", "virtual phone system for small business, $14-$80/mo"),
        ("Google Business Messages", "free messaging via Google Business Profile"),
        ("Facebook Messenger for Business", "free messaging, limited automation"),
        ("WhatsApp Business", "free messaging app, no voice AI"),
        ("generic voicemail", "free with phone plan, zero intelligence"),
        ("phone answering service (human)", "general human answering services $1-3 per call"),
        ("spouse/family answering phone", "free but unreliable and unprofessional"),
        ("apprentice answering phone", "paid worker diverted from billable work"),
        ("ServiceM8 messaging", "trade job management with basic messaging"),
        ("Tradify", "trade job management software, no voice features"),
        ("Fergus", "trade management software, no AI voice"),
        ("Jobber", "field service management, basic communication features"),
        ("ServiceTitan", "enterprise trade management, $2,000+/mo, complex"),
        ("Housecall Pro", "field service management, $49-$169/mo"),
        ("CallRail", "call tracking and analytics, $45-$145/mo"),
        ("ClickFunnels with chatbot", "funnel builder with basic chat, $97-$297/mo"),
        ("Calendly", "scheduling tool, $8-$16/mo, no voice"),
        ("Acuity Scheduling", "online booking, $16-$50/mo, no voice interaction"),
        ("Podium", "customer communication platform, $399-$599/mo"),
        ("Birdeye", "reputation and communication platform, $300+/mo"),
        ("Thryv", "small business platform, phone + CRM, $199-$499/mo"),
    ]
    for competitor, description in competitors:
        stories.append({
            "agent_id": agent_id,
            "category": "competitive_comparison",
            "category_num": 10,
            "task_title": f"Comparison: vs {competitor}",
            "prompt": f"""Write a detailed competitive comparison: Sunaiva AI Voice Widget vs {competitor}.

**Competitor:** {competitor}
**Description:** {description}

Create a comprehensive comparison document:

1. **Quick Verdict** (2 sentences): Who wins and why
2. **Comparison Table**:
   | Feature | Sunaiva | {competitor} |
   Including: pricing, setup time, 24/7 availability, voice capability, AI intelligence,
   customisation, Australian support, integration options, scalability, contract terms
3. **Where {competitor} Wins**: Be honest about any advantages (builds credibility)
4. **Where Sunaiva Wins**: Our key advantages with specific details
5. **Cost Analysis**: 12-month total cost comparison for a typical tradie
   - Include hidden costs (per-minute, per-call, overage charges)
6. **Use Case Fit**: When would a tradie choose {competitor} vs Sunaiva
7. **Migration Guide**: If switching from {competitor}, what's involved
8. **SEO Snippet**: 2-sentence comparison for search snippets ("{competitor} alternative for tradies")
9. **Sales Battle Card**: 3 key talking points if a prospect mentions {competitor}
10. **Verdict for Tradies**: Specific recommendation for Australian trade businesses

Be fair but confident. Acknowledge competitor strengths while showing Sunaiva's unique value for the tradie market.
Australian pricing in AUD where possible. Focus on what matters to tradies: cost, simplicity, reliability."""
        })
        agent_id += 1

    return stories


async def execute_agent(
    session: aiohttp.ClientSession,
    story: dict,
    api_key: str
) -> AgentResult:
    """Execute a single agent task via OpenRouter API."""
    start_time = time.time()

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://github.com/genesis-system",
        "X-Title": "Genesis 500-Agent MiniMax Swarm"
    }

    payload = {
        "model": MINIMAX_MODEL_ID,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": story["prompt"]}
        ],
        "temperature": 0.7,
        "max_tokens": 4096
    }

    try:
        timeout = aiohttp.ClientTimeout(total=REQUEST_TIMEOUT)
        async with session.post(OPENROUTER_BASE_URL, json=payload, headers=headers, timeout=timeout) as response:
            response_time_ms = int((time.time() - start_time) * 1000)

            if response.status != 200:
                error_text = await response.text()
                return AgentResult(
                    agent_id=story["agent_id"],
                    category=story["category"],
                    category_num=story["category_num"],
                    task_title=story["task_title"],
                    status="fail",
                    prompt_tokens=0,
                    completion_tokens=0,
                    total_tokens=0,
                    cost_usd=0.0,
                    response_time_ms=response_time_ms,
                    error=f"HTTP {response.status}: {error_text[:300]}"
                )

            data = await response.json()

            # Check for error in response body
            if "error" in data:
                return AgentResult(
                    agent_id=story["agent_id"],
                    category=story["category"],
                    category_num=story["category_num"],
                    task_title=story["task_title"],
                    status="fail",
                    prompt_tokens=0,
                    completion_tokens=0,
                    total_tokens=0,
                    cost_usd=0.0,
                    response_time_ms=response_time_ms,
                    error=f"API Error: {json.dumps(data['error'])[:300]}"
                )

            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)
            total_tokens = usage.get("total_tokens", 0)

            # MiniMax M2.5 pricing via OpenRouter
            # Input: $1.00/MTok, Output: $5.50/MTok (approximate)
            cost_usd = (prompt_tokens / 1_000_000) * 1.00 + (completion_tokens / 1_000_000) * 5.50

            response_text = data["choices"][0]["message"]["content"]

            return AgentResult(
                agent_id=story["agent_id"],
                category=story["category"],
                category_num=story["category_num"],
                task_title=story["task_title"],
                status="success",
                prompt_tokens=prompt_tokens,
                completion_tokens=completion_tokens,
                total_tokens=total_tokens,
                cost_usd=cost_usd,
                response_time_ms=response_time_ms,
                response=response_text
            )

    except asyncio.TimeoutError:
        response_time_ms = int((time.time() - start_time) * 1000)
        return AgentResult(
            agent_id=story["agent_id"],
            category=story["category"],
            category_num=story["category_num"],
            task_title=story["task_title"],
            status="fail",
            prompt_tokens=0,
            completion_tokens=0,
            total_tokens=0,
            cost_usd=0.0,
            response_time_ms=response_time_ms,
            error=f"Timeout after {REQUEST_TIMEOUT}s"
        )
    except Exception as e:
        response_time_ms = int((time.time() - start_time) * 1000)
        return AgentResult(
            agent_id=story["agent_id"],
            category=story["category"],
            category_num=story["category_num"],
            task_title=story["task_title"],
            status="fail",
            prompt_tokens=0,
            completion_tokens=0,
            total_tokens=0,
            cost_usd=0.0,
            response_time_ms=response_time_ms,
            error=str(e)[:300]
        )


async def main():
    """Main orchestrator for 500-agent swarm."""
    print(f"\n{'='*80}")
    print("GENESIS 500-AGENT MINIMAX M2.5 SWARM")
    print("Sunaiva Talking Widget Content Generation")
    print(f"{'='*80}")
    print(f"Timestamp: {datetime.now().isoformat()}")
    print(f"Model: {MINIMAX_MODEL_ID}")
    print(f"Batch Size: {BATCH_SIZE}")
    print(f"Request Timeout: {REQUEST_TIMEOUT}s")
    print(f"Output: {OUTPUT_DIR}")
    print(f"{'='*80}\n")

    # Generate all 500 stories
    print("Generating 500 stories across 10 categories...")
    stories = generate_stories()
    print(f"Generated {len(stories)} stories\n")

    # Create output directories
    category_dirs = {
        1: "category_01_widget_customization",
        2: "category_02_faq_content",
        3: "category_03_objection_handling",
        4: "category_04_widget_prompts",
        5: "category_05_seo_blog_content",
        6: "category_06_social_media",
        7: "category_07_email_subjects",
        8: "category_08_partner_pitches",
        9: "category_09_success_stories",
        10: "category_10_competitive_comparison",
    }
    for cat_dir in category_dirs.values():
        os.makedirs(f"{OUTPUT_DIR}/{cat_dir}", exist_ok=True)

    # Execute in batches
    all_results = []
    total_stories = len(stories)
    total_batches = (total_stories + BATCH_SIZE - 1) // BATCH_SIZE

    start_time = time.time()

    async with aiohttp.ClientSession() as session:
        for i in range(0, total_stories, BATCH_SIZE):
            batch = stories[i:i + BATCH_SIZE]
            batch_num = (i // BATCH_SIZE) + 1

            print(f"Batch {batch_num}/{total_batches}: Firing {len(batch)} agents (#{batch[0]['agent_id']}-#{batch[-1]['agent_id']})...")

            try:
                batch_results = await asyncio.wait_for(
                    asyncio.gather(
                        *[execute_agent(session, story, API_KEY) for story in batch]
                    ),
                    timeout=BATCH_TIMEOUT
                )

                all_results.extend(batch_results)

                successes = len([r for r in batch_results if r.status == "success"])
                failures = len([r for r in batch_results if r.status == "fail"])
                batch_cost = sum(r.cost_usd for r in batch_results)

                print(f"  OK: {successes} success, {failures} failed, ${batch_cost:.4f}")

                # Save individual results immediately
                for result in batch_results:
                    cat_dir = category_dirs.get(result.category_num, "uncategorized")
                    filepath = f"{OUTPUT_DIR}/{cat_dir}/agent_{result.agent_id:03d}.json"
                    with open(filepath, "w") as f:
                        json.dump(asdict(result), f, indent=2)

            except asyncio.TimeoutError:
                print(f"  TIMEOUT: Batch {batch_num} timed out after {BATCH_TIMEOUT}s")
                for story in batch:
                    result = AgentResult(
                        agent_id=story["agent_id"],
                        category=story["category"],
                        category_num=story["category_num"],
                        task_title=story["task_title"],
                        status="fail",
                        prompt_tokens=0,
                        completion_tokens=0,
                        total_tokens=0,
                        cost_usd=0.0,
                        response_time_ms=BATCH_TIMEOUT * 1000,
                        error=f"Batch timeout after {BATCH_TIMEOUT}s"
                    )
                    all_results.append(result)

            # Brief pause between batches
            if i + BATCH_SIZE < total_stories:
                await asyncio.sleep(INTER_BATCH_DELAY)

    elapsed_seconds = time.time() - start_time

    # Save all results to JSONL
    jsonl_path = f"{OUTPUT_DIR}/all_results.jsonl"
    with open(jsonl_path, "w") as f:
        for result in all_results:
            f.write(json.dumps(asdict(result)) + "\n")

    # Calculate metrics
    total_agents = len(all_results)
    total_successes = len([r for r in all_results if r.status == "success"])
    total_failures = len([r for r in all_results if r.status == "fail"])
    success_rate = (total_successes / total_agents * 100) if total_agents > 0 else 0
    total_tokens = sum(r.total_tokens for r in all_results)
    total_cost = sum(r.cost_usd for r in all_results)
    avg_response = sum(r.response_time_ms for r in all_results) / total_agents if total_agents > 0 else 0

    # Category breakdown
    category_stats = {}
    for r in all_results:
        cat = r.category
        if cat not in category_stats:
            category_stats[cat] = {"total": 0, "success": 0, "fail": 0, "cost": 0.0, "tokens": 0}
        category_stats[cat]["total"] += 1
        if r.status == "success":
            category_stats[cat]["success"] += 1
        else:
            category_stats[cat]["fail"] += 1
        category_stats[cat]["cost"] += r.cost_usd
        category_stats[cat]["tokens"] += r.total_tokens

    # Generate report
    report = f"""# MiniMax 500-Agent Swarm Report
## Sunaiva Talking Widget Content Generation

**Generated:** {datetime.now().isoformat()}
**Model:** {MINIMAX_MODEL_ID}
**Elapsed Time:** {elapsed_seconds:.1f}s ({elapsed_seconds/60:.1f} minutes)

## Overview

| Metric | Value |
|--------|-------|
| **Total Agents Fired** | {total_agents} |
| **Successful** | {total_successes} ({success_rate:.1f}%) |
| **Failed** | {total_failures} |
| **Total Tokens** | {total_tokens:,} |
| **Total Cost** | ${total_cost:.4f} |
| **Avg Response Time** | {avg_response:.0f}ms |
| **Cost Per Agent** | ${total_cost/total_agents:.4f} |

## Category Breakdown

| # | Category | Total | Success | Failed | Tokens | Cost |
|---|----------|-------|---------|--------|--------|------|
"""

    category_names = {
        "widget_customization": "Widget Customization",
        "faq_content": "FAQ Content",
        "objection_handling": "Objection Handling",
        "widget_prompts": "Widget Prompts",
        "seo_blog_content": "SEO Blog Content",
        "social_media": "Social Media Posts",
        "email_subjects": "Email Subject Lines",
        "partner_pitches": "Partner Pitches",
        "success_stories": "Success Stories",
        "competitive_comparison": "Competitive Comparisons",
    }

    cat_num = 1
    for cat_key in ["widget_customization", "faq_content", "objection_handling", "widget_prompts",
                     "seo_blog_content", "social_media", "email_subjects", "partner_pitches",
                     "success_stories", "competitive_comparison"]:
        stats = category_stats.get(cat_key, {"total": 0, "success": 0, "fail": 0, "cost": 0.0, "tokens": 0})
        name = category_names.get(cat_key, cat_key)
        report += f"| {cat_num} | {name} | {stats['total']} | {stats['success']} | {stats['fail']} | {stats['tokens']:,} | ${stats['cost']:.4f} |\n"
        cat_num += 1

    # Add errors section
    errors = [r for r in all_results if r.status == "fail"]
    if errors:
        report += f"\n## Errors ({len(errors)} failures)\n\n"
        # Group by error message
        error_groups = {}
        for r in errors:
            err = r.error or "Unknown"
            if err not in error_groups:
                error_groups[err] = []
            error_groups[err].append(r.agent_id)
        for err, agent_ids in error_groups.items():
            report += f"- **{err}**: Agents {', '.join(str(a) for a in agent_ids[:10])}"
            if len(agent_ids) > 10:
                report += f" (+{len(agent_ids)-10} more)"
            report += "\n"
    else:
        report += "\n## Errors\n\nNo errors! All 500 agents completed successfully.\n"

    report += f"""
## Output Files

- **Individual results:** `{OUTPUT_DIR}/category_XX_*/agent_NNN.json`
- **All results JSONL:** `{OUTPUT_DIR}/all_results.jsonl`
- **This report:** `{OUTPUT_DIR}/SWARM_REPORT.md`

## Cost Analysis

- **Total cost:** ${total_cost:.4f}
- **Cost per agent:** ${total_cost/total_agents:.4f}
- **Projected 1000 agents:** ${total_cost/total_agents*1000:.2f}
- **Model:** MiniMax M2.5 via OpenRouter

---

*Generated by Genesis 500-Agent MiniMax Swarm*
*Timestamp: {datetime.now().isoformat()}*
"""

    report_path = f"{OUTPUT_DIR}/SWARM_REPORT.md"
    with open(report_path, "w") as f:
        f.write(report)

    # Print summary
    print(f"\n{'='*80}")
    print("SWARM EXECUTION COMPLETE")
    print(f"{'='*80}")
    print(f"Total Agents: {total_agents}")
    print(f"Successes: {total_successes} ({success_rate:.1f}%)")
    print(f"Failures: {total_failures}")
    print(f"Total Tokens: {total_tokens:,}")
    print(f"Total Cost: ${total_cost:.4f}")
    print(f"Avg Response Time: {avg_response:.0f}ms")
    print(f"Elapsed Time: {elapsed_seconds:.1f}s ({elapsed_seconds/60:.1f} min)")
    print(f"\nReport: {report_path}")
    print(f"Results: {jsonl_path}")
    print(f"{'='*80}\n")


if __name__ == "__main__":
    asyncio.run(main())
