#!/usr/bin/env python3
"""
Session 23 Content Generation Swarm
Fire 200 agents via OpenRouter using MiniMax M2.5 for product launch content.

4 Batches:
- Batch 1: Product Testing Scripts (50 agents)
- Batch 2: Sales Collateral (50 agents)
- Batch 3: SEO Content for Domain Empire (50 agents)
- Batch 4: Email Templates (50 agents)

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

import os
import sys
import json
import asyncio
import time
from datetime import datetime
from typing import List, Dict, Any

sys.path.append('/mnt/e/genesis-system')

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 = "openai/gpt-3.5-turbo"  # Reliable, fast, and cheap for content generation
BATCH_SIZE = 20
REQUEST_TIMEOUT_SECONDS = 300
OUTPUT_DIR = "/mnt/e/genesis-system/swarm-output/session23"

# API Key
def load_api_key() -> str:
    """Load OpenRouter API key."""
    api_key = os.getenv('OPENROUTER_API_KEY')
    if api_key:
        return api_key

    credentials_file = "/mnt/e/genesis-system/Credentials/Genesis Credentials additions.txt"
    try:
        with open(credentials_file, 'r') as f:
            for line in f:
                if 'OpenRouter-Genesis-OpenClaw-API-KEY=' in line:
                    return line.split('=')[1].strip()
    except Exception as e:
        print(f"ERROR: Could not read credentials file: {e}")

    print("ERROR: OPENROUTER_API_KEY not found")
    sys.exit(1)


# Task Definitions
BATCH_1_TASKS = [
    # Product Testing Scripts (50 agents)
    {"id": 1, "task": "Create comprehensive black-box test scenarios for Sunaiva AI Memory upload flow, including file validation, size limits, format detection, and error handling", "type": "test"},
    {"id": 2, "task": "Write white-box test suite for Sunaiva AI Memory extraction pipeline, testing entity extraction, decision parsing, preference identification, and relationship mapping", "type": "test"},
    {"id": 3, "task": "Generate MCP tool response tests for Sunaiva Memory, verifying get_entities, search_decisions, get_preferences, get_relationships, query_vault, and export_vault tools", "type": "test"},
    {"id": 4, "task": "Create integration test scenarios for Sunaiva Memory auth flow, including signup, login, email verification, password reset, and session management", "type": "test"},
    {"id": 5, "task": "Write performance tests for Sunaiva Memory vault queries under load, testing 10, 100, 1000, 10000 conversations with response times and memory usage", "type": "test"},
    {"id": 6, "task": "Create test scenarios for Talking Widget embed code, testing shadow DOM isolation, CSS encapsulation, z-index conflicts, and responsive behavior", "type": "test"},
    {"id": 7, "task": "Write black-box tests for Talking Widget voice call initiation via Telnyx WebRTC, including microphone permissions, connection establishment, audio quality, and error states", "type": "test"},
    {"id": 8, "task": "Generate test suite for Talking Widget lead capture, validating form fields, email format, phone format, custom fields, and database storage", "type": "test"},
    {"id": 9, "task": "Create billing flow tests for Talking Widget, testing Stripe checkout, subscription creation, metering, overages, upgrades, downgrades, and cancellation", "type": "test"},
    {"id": 10, "task": "Write edge case tests for Talking Widget with large file uploads (100MB+), testing chunking, progress reporting, timeout handling, and resume capability", "type": "test"},
    {"id": 11, "task": "Create concurrent user tests for Talking Widget, simulating 10, 50, 100 simultaneous calls and validating call quality, connection stability, and resource usage", "type": "test"},
    {"id": 12, "task": "Write rate limiting tests for Talking Widget API, testing per-user limits, per-tier limits, burst allowances, and 429 response handling", "type": "test"},
    {"id": 13, "task": "Generate error handling tests for Sunaiva Memory, testing network failures, timeout scenarios, invalid tokens, expired sessions, and graceful degradation", "type": "test"},
    {"id": 14, "task": "Create API endpoint health tests for Sunaiva Memory backend, testing /health, /auth/*, /upload, /extract, /mcp/*, /billing/* with status codes and response formats", "type": "test"},
    {"id": 15, "task": "Write CRUD operation tests for Sunaiva Memory vault management, testing create, read, update, delete, search, and pagination of conversations", "type": "test"},
    {"id": 16, "task": "Generate security tests for Sunaiva Memory, including SQL injection attempts, XSS payloads, CSRF token validation, JWT tampering, and authorization bypass attempts", "type": "test"},
    {"id": 17, "task": "Create regression tests for Sunaiva Memory to ensure existing functionality (v1.0 features) still works after v2.0 updates", "type": "test"},
    {"id": 18, "task": "Write performance baseline tests for Talking Widget, measuring page load impact (LCP, FID, CLS), bundle size, API response times, and WebRTC latency", "type": "test"},
    {"id": 19, "task": "Generate cross-browser compatibility tests for Talking Widget, testing Chrome, Firefox, Safari, Edge with various versions and feature detection", "type": "test"},
    {"id": 20, "task": "Create mobile responsiveness tests for Talking Widget, testing iOS Safari, Android Chrome, tablet layouts, and touch interactions", "type": "test"},
    {"id": 21, "task": "Write accessibility tests for Talking Widget, validating WCAG 2.1 AA compliance, keyboard navigation, ARIA labels, screen reader compatibility, and focus management", "type": "test"},
    {"id": 22, "task": "Generate internationalization tests for Sunaiva Memory, testing UTF-8 handling, multi-language support, date/time formats, and currency display", "type": "test"},
    {"id": 23, "task": "Create webhook delivery tests for Talking Widget, validating lead capture webhooks, call recording webhooks, and retry logic on failure", "type": "test"},
    {"id": 24, "task": "Write data migration tests for Sunaiva Memory, testing import from competitors (ChatGPT, Claude, Gemini exports) with schema validation and error reporting", "type": "test"},
    {"id": 25, "task": "Generate analytics tracking tests for Talking Widget, verifying event firing for widget load, call start, call end, lead submit, upgrade click", "type": "test"},
    {"id": 26, "task": "Create memory extraction accuracy tests for Sunaiva Memory, comparing extracted entities against ground truth datasets with precision/recall metrics", "type": "test"},
    {"id": 27, "task": "Write voice quality tests for Talking Widget, measuring MOS scores, audio codec selection, bandwidth adaptation, and background noise handling", "type": "test"},
    {"id": 28, "task": "Generate subscription lifecycle tests for Sunaiva Memory, testing trial start, trial end, payment success, payment failure, dunning, and reactivation flows", "type": "test"},
    {"id": 29, "task": "Create disaster recovery tests for Sunaiva Memory, simulating database failures, cache evictions, and service outages with RTO/RPO validation", "type": "test"},
    {"id": 30, "task": "Write timezone handling tests for Sunaiva Memory, validating UTC storage, user timezone display, and DST transitions", "type": "test"},
    {"id": 31, "task": "Generate file format compatibility tests for Sunaiva Memory, testing Claude exports (JSON), ChatGPT exports (JSON/ZIP), Gemini exports (JSON), and generic JSONL/CSV", "type": "test"},
    {"id": 32, "task": "Create MCP server registration tests for Sunaiva Memory, validating Claude Desktop config, Cursor config, and server health checks", "type": "test"},
    {"id": 33, "task": "Write real-time update tests for Talking Widget dashboard, validating WebSocket connections, live call status, real-time analytics, and connection recovery", "type": "test"},
    {"id": 34, "task": "Generate white-label tests for Talking Widget, validating custom branding, logo upload, color scheme changes, and CNAME domain mapping", "type": "test"},
    {"id": 35, "task": "Create API authentication tests for Talking Widget, testing API key generation, rotation, revocation, and permission scopes", "type": "test"},
    {"id": 36, "task": "Write partner commission tests for Talking Widget agency model, validating 30% commission calculation, payout tracking, and monthly statements", "type": "test"},
    {"id": 37, "task": "Generate onboarding flow tests for Sunaiva Memory, testing welcome email, setup wizard, first upload, MCP installation, and success metrics", "type": "test"},
    {"id": 38, "task": "Create usage metering tests for Talking Widget, validating Telnyx minute tracking, billing reconciliation, and overage charges", "type": "test"},
    {"id": 39, "task": "Write admin panel tests for Talking Widget, testing customer management, usage analytics, billing overrides, and support tools", "type": "test"},
    {"id": 40, "task": "Generate compliance tests for Talking Widget voice data, validating GDPR consent, data retention policies, deletion requests, and audit logs", "type": "test"},
    {"id": 41, "task": "Create load balancing tests for Sunaiva Memory, simulating traffic spikes and validating auto-scaling, connection pooling, and cache hit rates", "type": "test"},
    {"id": 42, "task": "Write webhook signature verification tests for Talking Widget, validating HMAC signing, timestamp validation, and replay attack prevention", "type": "test"},
    {"id": 43, "task": "Generate multi-tenancy tests for Sunaiva Memory, validating data isolation, resource quotas, and cross-tenant data leakage prevention", "type": "test"},
    {"id": 44, "task": "Create backup and restore tests for Sunaiva Memory, testing automated backups, point-in-time recovery, and data integrity validation", "type": "test"},
    {"id": 45, "task": "Write search accuracy tests for Sunaiva Memory vault, testing full-text search, semantic search, fuzzy matching, and relevance ranking", "type": "test"},
    {"id": 46, "task": "Generate integration tests for Talking Widget with CRM systems, testing Salesforce sync, HubSpot sync, GHL sync, and custom webhooks", "type": "test"},
    {"id": 47, "task": "Create notification tests for Sunaiva Memory, validating email notifications, in-app alerts, Slack integration, and delivery guarantees", "type": "test"},
    {"id": 48, "task": "Write fraud detection tests for Talking Widget, testing duplicate signups, credit card testing attempts, and bot traffic filtering", "type": "test"},
    {"id": 49, "task": "Generate version compatibility tests for Sunaiva Memory MCP server, testing compatibility with Claude Desktop 1.x, 2.x, Cursor 0.x versions", "type": "test"},
    {"id": 50, "task": "Create API documentation tests for both Sunaiva Memory and Talking Widget, validating OpenAPI spec completeness, example accuracy, and Postman collection", "type": "test"},
]

BATCH_2_TASKS = [
    # Sales Collateral (50 agents)
    {"id": 51, "task": "Write a case study: Australian real estate agency uses Talking Widget to capture 300 leads/month, 18% conversion rate, $89K revenue increase in 90 days", "type": "sales"},
    {"id": 52, "task": "Create a case study: Plumbing company uses Talking Widget for after-hours calls, 40% reduction in missed opportunities, 5-star Google review increase", "type": "sales"},
    {"id": 53, "task": "Write a case study: SaaS founder uses Sunaiva AI Memory to maintain context across 2,000 ChatGPT conversations, saves 15hrs/week re-explaining context", "type": "sales"},
    {"id": 54, "task": "Create a case study: Marketing agency white-labels Talking Widget for 50 clients, $28K MRR in 6 months with 30% commission model", "type": "sales"},
    {"id": 55, "task": "Write a case study: E-commerce store uses Talking Widget for product support, 85% resolution rate, 2-minute average handling time, NPS score 78", "type": "sales"},
    {"id": 56, "task": "Create ROI calculator for agencies considering Talking Widget partnership: input client count, output MRR projection, commission earnings, setup time ROI", "type": "sales"},
    {"id": 57, "task": "Write ROI calculator for businesses buying Talking Widget: input missed calls/month, average deal value, output revenue recovered, payback period", "type": "sales"},
    {"id": 58, "task": "Create ROI calculator for Sunaiva AI Memory: input hours spent re-explaining context, hourly rate, output annual savings, productivity gain percentage", "type": "sales"},
    {"id": 59, "task": "Write comparison page: Sunaiva AI Memory vs Drift (pricing, features, MCP support, AI platform coverage, data ownership)", "type": "sales"},
    {"id": 60, "task": "Create comparison page: Sunaiva AI Memory vs Intercom (live chat vs memory vault, pricing, integrations, use cases)", "type": "sales"},
    {"id": 61, "task": "Write comparison page: Sunaiva AI Memory vs LiveChat (real-time vs persistent memory, AI assistant compatibility, cost comparison)", "type": "sales"},
    {"id": 62, "task": "Create comparison page: Talking Widget vs CallRail (features, pricing, AI voice quality, Australian market focus)", "type": "sales"},
    {"id": 63, "task": "Write comparison page: Talking Widget vs Dialpad AI (cost per minute, voice quality, ease of setup, integrations)", "type": "sales"},
    {"id": 64, "task": "Create FAQ page for Sunaiva AI Memory end customers: What is AI Memory? How does MCP work? Which platforms supported? Data privacy? Pricing tiers?", "type": "sales"},
    {"id": 65, "task": "Write FAQ page for Talking Widget end customers: What is AI voice? Call costs? Setup time? Widget customization? Integrations? Cancellation policy?", "type": "sales"},
    {"id": 66, "task": "Create FAQ page for Talking Widget agency partners: Commission structure? White-label options? Client support? Payment terms? Training provided?", "type": "sales"},
    {"id": 67, "task": "Write objection handling script: 'AI memory sounds gimmicky' → Address with concrete use cases, time savings metrics, and competitor adoption stats", "type": "sales"},
    {"id": 68, "task": "Create objection handling script: 'We already have a chatbot' → Differentiate voice quality, AI conversation depth, and Australian accent authenticity", "type": "sales"},
    {"id": 69, "task": "Write objection handling script: 'Too expensive for small business' → Break down cost per lead, compare to hiring receptionist, show ROI calculator", "type": "sales"},
    {"id": 70, "task": "Create objection handling script: 'Data privacy concerns' → Address encryption, data ownership, GDPR compliance, Australian data residency", "type": "sales"},
    {"id": 71, "task": "Write objection handling script: 'Setup sounds complicated' → Emphasize 5-minute widget embed, white-glove onboarding, video tutorials", "type": "sales"},
    {"id": 72, "task": "Create one-pager for Talking Widget targeting tradies: value prop, pricing, setup, testimonial, CTA with QR code for mobile", "type": "sales"},
    {"id": 73, "task": "Write one-pager for Sunaiva AI Memory targeting developers: technical architecture, MCP protocol, supported platforms, API access, pricing", "type": "sales"},
    {"id": 74, "task": "Create one-pager for Talking Widget agency partnership: commission model, white-label options, client count projection, partner benefits", "type": "sales"},
    {"id": 75, "task": "Write sales script for cold calling tradies: intro, pain point identification (missed calls), Talking Widget pitch, objection handling, close", "type": "sales"},
    {"id": 76, "task": "Create sales script for agency partnership outreach: intro, identify website client base, pitch recurring commission model, schedule demo", "type": "sales"},
    {"id": 77, "task": "Write email sales sequence for Sunaiva AI Memory (5 emails): Day 0 intro, Day 2 use cases, Day 5 case study, Day 8 comparison, Day 12 discount", "type": "sales"},
    {"id": 78, "task": "Create email sales sequence for Talking Widget tradies (5 emails): Day 0 pain point, Day 3 solution, Day 7 testimonial, Day 10 ROI, Day 14 trial", "type": "sales"},
    {"id": 79, "task": "Write sales battlecard for Sunaiva AI Memory: positioning, key features, competitive differentiators, pricing, objection responses, closing techniques", "type": "sales"},
    {"id": 80, "task": "Create sales battlecard for Talking Widget: target personas, pain points, value props, feature highlights, pricing options, demo script", "type": "sales"},
    {"id": 81, "task": "Write product demo script for Sunaiva AI Memory: upload ChatGPT export, show extraction results, demo MCP tools in Claude, highlight time saved", "type": "sales"},
    {"id": 82, "task": "Create product demo script for Talking Widget: show embed code, make live test call, demonstrate lead capture, review dashboard analytics", "type": "sales"},
    {"id": 83, "task": "Write win/loss analysis framework: track why deals close (features, pricing, trust) and why they fall through (cost, complexity, competitors)", "type": "sales"},
    {"id": 84, "task": "Create partner onboarding checklist for Talking Widget agencies: account setup, branding customization, client training, commission setup, support access", "type": "sales"},
    {"id": 85, "task": "Write customer success playbook for Sunaiva AI Memory: onboarding milestones, usage triggers, expansion opportunities, churn prevention", "type": "sales"},
    {"id": 86, "task": "Create upsell guide for Talking Widget: identify upgrade triggers (usage patterns), timing strategy, feature showcase, price anchoring", "type": "sales"},
    {"id": 87, "task": "Write referral program design for Sunaiva AI Memory: reward structure (20% off for referrer, 10% off for referee), tracking, terms", "type": "sales"},
    {"id": 88, "task": "Create proposal template for Talking Widget enterprise deals: executive summary, solution overview, pricing, implementation timeline, ROI projection", "type": "sales"},
    {"id": 89, "task": "Write testimonial collection guide: when to ask (after success milestone), email template, video script, incentive options", "type": "sales"},
    {"id": 90, "task": "Create pricing justification document for Sunaiva AI Memory Sovereign tier ($197/mo): costs (LLM extraction, storage, MCP serving), margin breakdown, value delivered", "type": "sales"},
    {"id": 91, "task": "Write competitive intelligence report: top 5 AI memory competitors (features, pricing, market position, weaknesses, our advantages)", "type": "sales"},
    {"id": 92, "task": "Create sales enablement toolkit: product sheets, demo videos, case studies, ROI calculators, comparison pages, objection scripts (organized zip)", "type": "sales"},
    {"id": 93, "task": "Write partnership pitch deck for Talking Widget: market opportunity, product overview, agency model economics, success stories, call to action (10 slides)", "type": "sales"},
    {"id": 94, "task": "Create lead qualification framework (BANT): Budget (pricing tier), Authority (decision maker), Need (missed calls/context loss), Timeline (urgency)", "type": "sales"},
    {"id": 95, "task": "Write customer retention strategy: usage monitoring, proactive support, quarterly business reviews, feature education, loyalty rewards", "type": "sales"},
    {"id": 96, "task": "Create churn prevention playbook: early warning signals (usage drop, support tickets, payment failures), intervention strategies, win-back campaigns", "type": "sales"},
    {"id": 97, "task": "Write sales forecasting model: pipeline stages, conversion rates, average deal size, sales cycle length, monthly MRR projection", "type": "sales"},
    {"id": 98, "task": "Create account-based marketing plan for Talking Widget: target agency list (50-200 clients each), personalized outreach, multi-touch campaigns", "type": "sales"},
    {"id": 99, "task": "Write value proposition canvas for Sunaiva AI Memory: customer jobs, pains, gains, products/services, pain relievers, gain creators", "type": "sales"},
    {"id": 100, "task": "Create sales compensation plan: base salary, commission tiers (5% up to $10K MRR, 7% above), accelerators, team bonuses, SPIFs", "type": "sales"},
]

BATCH_3_TASKS = [
    # SEO Content for Domain Empire (50 agents)
    {"id": 101, "task": "Write 800-word SEO blog post for plumber-sydney.com: 'Top 10 Signs You Need Emergency Plumbing Services in Sydney' with local keywords, FAQ schema", "type": "seo"},
    {"id": 102, "task": "Create 1000-word guide for electrician-melbourne.com: 'Complete Guide to Electrical Safety Inspections for Melbourne Homes' with safety tips, cost breakdown", "type": "seo"},
    {"id": 103, "task": "Write 700-word post for aircon-brisbane.com: 'Brisbane Air Conditioning Installation: Costs, Best Brands, and What to Expect' with comparison table", "type": "seo"},
    {"id": 104, "task": "Create 900-word article for roofing-perth.com: 'Perth Roof Restoration vs Replacement: Which Is Right for Your Home?' with decision tree", "type": "seo"},
    {"id": 105, "task": "Write 850-word guide for carpenter-adelaide.com: 'Adelaide Custom Carpentry: Kitchen Renovation Costs and Timeline Guide' with photo examples", "type": "seo"},
    {"id": 106, "task": "Create meta descriptions and title tags (10 variations each) for plumber-sydney.com pages: home, services, emergency, contact, about", "type": "seo"},
    {"id": 107, "task": "Write meta descriptions and title tags (10 variations each) for electrician-melbourne.com pages: residential, commercial, solar, safety, reviews", "type": "seo"},
    {"id": 108, "task": "Create local SEO content for cairns-plumber.com: 'Why Cairns Homeowners Trust [Business Name] for Plumbing Services' with local landmarks, testimonials", "type": "seo"},
    {"id": 109, "task": "Write local SEO page for goldcoast-aircon.com: 'Gold Coast Air Conditioning Experts: Servicing Surfers Paradise, Broadbeach, Burleigh Heads' with suburb focus", "type": "seo"},
    {"id": 110, "task": "Create long-tail keyword article for sydney-emergency-plumber.com: 'Burst Pipe at 2AM? Here's What to Do Before the Plumber Arrives' with step-by-step guide", "type": "seo"},
    {"id": 111, "task": "Write long-tail post for melbourne-solar-electrician.com: 'Tesla Powerwall Installation Melbourne: Is It Worth It in 2026?' with ROI calculator, rebates", "type": "seo"},
    {"id": 112, "task": "Create service area page for brisbane-plumbing.com: 'Plumbing Services in [Suburb Name]' template optimized for 20 Brisbane suburbs with local schema", "type": "seo"},
    {"id": 113, "task": "Write FAQ page for perth-electrician.com: 20 common questions (licensing, costs, safety, emergency, commercial) with rich snippets markup", "type": "seo"},
    {"id": 114, "task": "Create comparison page for adelaide-roofing.com: 'Metal Roofing vs Tile Roofing in Adelaide: Pros, Cons, Costs' with side-by-side table", "type": "seo"},
    {"id": 115, "task": "Write seasonal content for sydney-aircon.com: 'Preparing Your Air Conditioner for Sydney's Summer: Maintenance Checklist' with timing tips", "type": "seo"},
    {"id": 116, "task": "Create ultimate guide for melbourne-renovations.com: '2026 Melbourne Home Renovation Cost Guide: Kitchen, Bathroom, Extensions' 2500 words with infographic", "type": "seo"},
    {"id": 117, "task": "Write case study for brisbane-plumber.com: 'How We Saved a Brisbane Family $8,000 on Water Damage Repairs' with before/after photos, timeline", "type": "seo"},
    {"id": 118, "task": "Create listicle for perth-landscaping.com: '15 Drought-Tolerant Plants Perfect for Perth Gardens' with care guides, water usage", "type": "seo"},
    {"id": 119, "task": "Write how-to guide for sydney-handyman.com: 'DIY vs Professional: When to Call a Handyman in Sydney' with cost-benefit analysis", "type": "seo"},
    {"id": 120, "task": "Create neighborhood guide for melbourne-plumber.com: 'Older Homes in Fitzroy: Common Plumbing Issues and Solutions' with heritage home focus", "type": "seo"},
    {"id": 121, "task": "Write regulatory content for brisbane-electrician.com: 'Understanding Queensland Electrical Safety Regulations for Homeowners' with compliance checklist", "type": "seo"},
    {"id": 122, "task": "Create cost breakdown page for adelaide-landscaping.com: 'Adelaide Landscaping Costs 2026: What You'll Pay for Gardens, Decking, Paving' with price ranges", "type": "seo"},
    {"id": 123, "task": "Write comparison guide for cairns-aircon.com: 'Ducted vs Split System Air Conditioning for Cairns Homes: Which Suits Your Climate?' with climate data", "type": "seo"},
    {"id": 124, "task": "Create local business profile for goldcoast-builder.com: 'About [Business Name]: Gold Coast's Most Trusted Home Builders Since 2005' with awards, team", "type": "seo"},
    {"id": 125, "task": "Write emergency guide for sydney-locksmith.com: 'Locked Out in Sydney? Here's What to Do (And What Not to Do)' with safety tips, costs", "type": "seo"},
    {"id": 126, "task": "Create seasonal prep guide for melbourne-roofing.com: 'Melbourne Roof Maintenance Before Storm Season: Inspector's Checklist' with photo guide", "type": "seo"},
    {"id": 127, "task": "Write buyer's guide for brisbane-solar.com: 'Brisbane Solar Panel Buyers Guide 2026: Brands, Costs, Rebates, ROI' with calculator", "type": "seo"},
    {"id": 128, "task": "Create troubleshooting guide for perth-plumber.com: '10 Common Plumbing Problems in Perth Homes (And When to Call a Pro)' with DIY tips", "type": "seo"},
    {"id": 129, "task": "Write installation guide for adelaide-aircon.com: 'Adelaide Air Conditioning Installation: Timeline, Disruption, and What to Expect' with day-by-day breakdown", "type": "seo"},
    {"id": 130, "task": "Create maintenance guide for sydney-painter.com: 'How Often Should You Repaint Your Sydney Home? Coastal Climate Considerations' with paint lifespan data", "type": "seo"},
    {"id": 131, "task": "Write licensing explainer for melbourne-builder.com: 'Understanding Melbourne Building Permits: Do You Need One for Your Project?' with permit types", "type": "seo"},
    {"id": 132, "task": "Create warranty guide for brisbane-roofing.com: 'Roof Warranty in Brisbane: What's Covered, What's Not, and How Long?' with warranty comparison", "type": "seo"},
    {"id": 133, "task": "Write insurance guide for perth-plumber.com: 'Will Insurance Cover My Perth Plumbing Emergency? Claims Guide' with claims process", "type": "seo"},
    {"id": 134, "task": "Create financing guide for adelaide-renovations.com: 'Financing Your Adelaide Home Renovation: Loans, Grants, and Payment Plans' with lender comparison", "type": "seo"},
    {"id": 135, "task": "Write sustainability guide for cairns-builder.com: 'Building Eco-Friendly Homes in Cairns: Materials, Design, and Certifications' with green building tips", "type": "seo"},
    {"id": 136, "task": "Create technology guide for goldcoast-electrician.com: 'Smart Home Electrical Setup on the Gold Coast: Lighting, Security, Energy Management' with product recs", "type": "seo"},
    {"id": 137, "task": "Write restoration guide for sydney-heritage-builder.com: 'Renovating Heritage Homes in Sydney: Council Approvals and Preservation Requirements' with case examples", "type": "seo"},
    {"id": 138, "task": "Create energy efficiency guide for melbourne-insulation.com: 'Melbourne Home Insulation Guide: R-Values, Costs, and Energy Savings' with savings calculator", "type": "seo"},
    {"id": 139, "task": "Write water conservation guide for brisbane-plumber.com: 'Brisbane Water Restrictions and Plumbing Solutions for Water-Efficient Homes' with fixture recs", "type": "seo"},
    {"id": 140, "task": "Create bushfire prep guide for perth-landscaping.com: 'Bushfire-Safe Landscaping for Perth Hills: Plant Selection and Defensible Space' with zone map", "type": "seo"},
    {"id": 141, "task": "Write termite guide for adelaide-pest-control.com: 'Adelaide Termite Inspection and Treatment: Costs, Timing, and Prevention' with inspection checklist", "type": "seo"},
    {"id": 142, "task": "Create pool guide for cairns-pool-builder.com: 'Building a Pool in Cairns: Permits, Costs, and Tropical Climate Considerations' with design gallery", "type": "seo"},
    {"id": 143, "task": "Write deck guide for goldcoast-carpenter.com: 'Gold Coast Deck Building: Timber vs Composite, Costs, and Coastal Durability' with material comparison", "type": "seo"},
    {"id": 144, "task": "Create gutter guide for sydney-roofing.com: 'Sydney Gutter Installation and Cleaning: Preventing Water Damage in Heavy Rain' with maintenance schedule", "type": "seo"},
    {"id": 145, "task": "Write ventilation guide for melbourne-hvac.com: 'Melbourne Home Ventilation: Mould Prevention and Indoor Air Quality Solutions' with health benefits", "type": "seo"},
    {"id": 146, "task": "Create kitchen guide for brisbane-renovations.com: 'Brisbane Kitchen Renovation Trends 2026: Layouts, Materials, and Smart Appliances' with trend photos", "type": "seo"},
    {"id": 147, "task": "Write bathroom guide for perth-tiler.com: 'Perth Bathroom Tiling: Choosing Tiles for Coastal Humidity and Style' with tile showcase", "type": "seo"},
    {"id": 148, "task": "Create extension guide for adelaide-builder.com: 'Adelaide Home Extensions: Second Storey vs Rear Extension Costs and Regulations' with 3D renders", "type": "seo"},
    {"id": 149, "task": "Write granny flat guide for sydney-builder.com: 'Sydney Granny Flat Approvals 2026: CDC Process, Costs, and Rental Income Potential' with ROI calc", "type": "seo"},
    {"id": 150, "task": "Create solar battery guide for melbourne-solar.com: 'Melbourne Solar Battery Storage: Tesla vs Sonnen vs Enphase Comparison and Payback Period' with specs table", "type": "seo"},
]

BATCH_4_TASKS = [
    # Email Templates (50 agents)
    {"id": 151, "task": "Write onboarding email 1 (welcome) for Sunaiva AI Memory: Thank you for signing up, here's what to expect, quick start guide link, support contact", "type": "email"},
    {"id": 152, "task": "Create onboarding email 2 (setup guide) for Sunaiva AI Memory: Step-by-step MCP installation for Claude Desktop, video tutorial, troubleshooting tips", "type": "email"},
    {"id": 153, "task": "Write onboarding email 3 (first success) for Sunaiva AI Memory: Congratulations on your first upload! Here's how to explore your vault, MCP tool demo", "type": "email"},
    {"id": 154, "task": "Create onboarding email 4 (tips) for Sunaiva AI Memory: 5 ways to get more value from your memory vault, advanced features, use case examples", "type": "email"},
    {"id": 155, "task": "Write onboarding email 5 (upgrade nudge) for Sunaiva AI Memory: You're at 180/200 conversations, upgrade to Pro for 500, special early adopter discount", "type": "email"},
    {"id": 156, "task": "Create welcome email for Talking Widget customers: Account activated, here's your embed code, setup video, test your widget link", "type": "email"},
    {"id": 157, "task": "Write setup guide email for Talking Widget: Installing your widget in 5 minutes, WordPress/Webflow/Wix/custom HTML instructions, preview link", "type": "email"},
    {"id": 158, "task": "Create first lead email for Talking Widget: Congratulations! Your widget captured its first lead, view dashboard, next steps to optimize conversions", "type": "email"},
    {"id": 159, "task": "Write tips email for Talking Widget: 7 ways to increase widget engagement, placement best practices, A/B testing ideas, case study link", "type": "email"},
    {"id": 160, "task": "Create churn prevention email 1 (low usage) for Sunaiva AI Memory: We noticed you haven't uploaded in 30 days, need help? Here are quick use cases", "type": "email"},
    {"id": 161, "task": "Write churn prevention email 2 (payment failure) for Sunaiva AI Memory: Your payment didn't go through, update payment method to avoid service interruption", "type": "email"},
    {"id": 162, "task": "Create churn prevention email 3 (cancellation feedback) for Sunaiva AI Memory: Sorry to see you go, can you tell us why? 50% off for 3 months to reconsider", "type": "email"},
    {"id": 163, "task": "Write win-back email for Sunaiva AI Memory churned customers: We've added new features (list 3), here's 60% off to come back, limited time offer", "type": "email"},
    {"id": 164, "task": "Create feature announcement email for Sunaiva AI Memory: NEW - Gemini export support is live! Upload your Gemini conversations, try it now", "type": "email"},
    {"id": 165, "task": "Write feature announcement email for Talking Widget: NEW - CRM integrations are here! Connect Salesforce, HubSpot, GHL with one click, setup guide", "type": "email"},
    {"id": 166, "task": "Create monthly usage report email for Sunaiva AI Memory: Your January stats - 342 conversations, 1,247 entities, 89 searches, upgrade to unlock more", "type": "email"},
    {"id": 167, "task": "Write monthly usage report email for Talking Widget: Your January stats - 127 calls, 43 leads, 18 conversions, $12K revenue attributed, analytics dashboard", "type": "email"},
    {"id": 168, "task": "Create upgrade nudge email (Starter to Pro) for Sunaiva AI Memory: You're at 195/200 conversations, upgrade now to avoid hitting limit, Pro features preview", "type": "email"},
    {"id": 169, "task": "Write upgrade nudge email (Pro to Power) for Sunaiva AI Memory: You're using advanced features heavily, Power tier gives you 2,000 conversations + priority support", "type": "email"},
    {"id": 170, "task": "Create upgrade nudge email (Scale to Growth) for Talking Widget: Your call volume is trending up, Growth tier gives you unlimited calls + white-label", "type": "email"},
    {"id": 171, "task": "Write seasonal promotion email for Sunaiva AI Memory: End of Financial Year Sale - 40% off annual plans, save up to $710, ends June 30", "type": "email"},
    {"id": 172, "task": "Create seasonal promotion email for Talking Widget: Black Friday Special - 50% off first 3 months for new signups, limited to 100 customers", "type": "email"},
    {"id": 173, "task": "Write referral program email for Sunaiva AI Memory: Love Sunaiva? Refer a friend and you both get 20% off next month, unique referral link included", "type": "email"},
    {"id": 174, "task": "Create partner welcome email for Talking Widget agencies: Welcome to the partner program! Here's your dashboard, commission structure, client onboarding guide", "type": "email"},
    {"id": 175, "task": "Write partner monthly statement email for Talking Widget: Your January commission - 12 active clients, $3,640 MRR, $1,092 commission, payment processed", "type": "email"},
    {"id": 176, "task": "Create beta program invite email for Sunaiva AI Memory: You're invited to test Living Memory (AI that learns from your conversations), join beta, NDA required", "type": "email"},
    {"id": 177, "task": "Write customer testimonial request email for Talking Widget: We'd love to hear your success story! Record 2-minute video testimonial, get $100 account credit", "type": "email"},
    {"id": 178, "task": "Create customer case study participation email for Sunaiva AI Memory: Featured case study opportunity - we'll write it, you review, $500 Amazon gift card included", "type": "email"},
    {"id": 179, "task": "Write NPS survey email for Talking Widget: How likely are you to recommend us? (0-10 scale), optional feedback, takes 30 seconds", "type": "email"},
    {"id": 180, "task": "Create product feedback email for Sunaiva AI Memory: What's one feature you wish we had? Reply to this email, top 3 requests get built next quarter", "type": "email"},
    {"id": 181, "task": "Write webinar invite email for Talking Widget: Live Demo - Getting 100 Leads/Month with AI Voice Widgets, Thursday 2pm AEST, register now", "type": "email"},
    {"id": 182, "task": "Create office hours email for Sunaiva AI Memory: Join our weekly Zoom office hours - ask questions, see demos, meet the team, Fridays 4pm AEST", "type": "email"},
    {"id": 183, "task": "Write holiday greeting email for both products: Happy holidays from the Sunaiva team, year in review highlights, thank you for being a customer", "type": "email"},
    {"id": 184, "task": "Create account security email for Sunaiva AI Memory: New login detected from [location], was this you? If not, secure your account immediately", "type": "email"},
    {"id": 185, "task": "Write scheduled maintenance email for Talking Widget: Planned maintenance Sunday 2am-4am AEST, widgets remain functional, dashboard briefly unavailable", "type": "email"},
    {"id": 186, "task": "Create outage apology email for Sunaiva AI Memory: We're sorry for the 2-hour downtime yesterday, here's what happened, 1 week service credit applied", "type": "email"},
    {"id": 187, "task": "Write milestone celebration email for Talking Widget: You've captured 1,000 leads! Here's a custom report showing your ROI, share your success on LinkedIn", "type": "email"},
    {"id": 188, "task": "Create data export email for Sunaiva AI Memory: Your data export is ready, download link (expires in 7 days), instructions for importing elsewhere", "type": "email"},
    {"id": 189, "task": "Write GDPR deletion confirmation email for Talking Widget: Your account and data have been permanently deleted per your request, confirmation ID included", "type": "email"},
    {"id": 190, "task": "Create trial expiration warning email for Sunaiva AI Memory: Your 14-day trial ends in 3 days, upgrade now to keep your vault, special trial-to-paid discount", "type": "email"},
    {"id": 191, "task": "Write trial ended email for Talking Widget: Your trial has ended, upgrade to continue using your widget, data preserved for 30 days, pricing options", "type": "email"},
    {"id": 192, "task": "Create abandoned cart email for Sunaiva AI Memory: You left checkout open - complete your upgrade and get 15% off with code COMPLETE15, expires 24hrs", "type": "email"},
    {"id": 193, "task": "Write invoice email for Talking Widget: Your January invoice ($497) - download PDF, view usage breakdown, payment processed via Stripe ending 4242", "type": "email"},
    {"id": 194, "task": "Create overage warning email for Sunaiva AI Memory: You've used 2,150/2,000 conversations this month, $3 overage charge, consider upgrading to avoid fees", "type": "email"},
    {"id": 195, "task": "Write payment method update email for Talking Widget: Your card expires next month, update payment method now to avoid service interruption, secure link", "type": "email"},
    {"id": 196, "task": "Create annual renewal email for Sunaiva AI Memory: Your annual plan renews in 30 days ($950), billing date Jan 15, cancel anytime, manage subscription", "type": "email"},
    {"id": 197, "task": "Write educational email series 1/5 for Talking Widget: Understanding AI Voice Technology - How It Works, Quality Factors, and Why Ours Sounds Human", "type": "email"},
    {"id": 198, "task": "Create educational email series 2/5 for Talking Widget: Lead Capture Best Practices - When to Show Widget, What Questions to Ask, Follow-Up Timing", "type": "email"},
    {"id": 199, "task": "Write educational email series 3/5 for Talking Widget: Voice Widget Analytics - Interpreting Call Duration, Conversion Rates, and ROI Metrics", "type": "email"},
    {"id": 200, "task": "Create educational email series 4/5 for Talking Widget: Integration Guide - Connecting Your CRM, Zapier Workflows, and Webhook Automation", "type": "email"},
]

# Combine all tasks
ALL_TASKS = BATCH_1_TASKS + BATCH_2_TASKS + BATCH_3_TASKS + BATCH_4_TASKS


async def execute_agent(
    session: aiohttp.ClientSession,
    task_spec: Dict[str, Any],
    api_key: str
) -> Dict[str, Any]:
    """Execute a single agent task."""
    start_time = time.time()

    task_id = task_spec["id"]
    task = task_spec["task"]
    task_type = task_spec["type"]

    # System prompt based on task type
    system_prompts = {
        "test": "You are an expert QA engineer specializing in comprehensive test scenario design. Create detailed, production-ready test cases with specific inputs, expected outputs, edge cases, and validation criteria.",
        "sales": "You are an expert sales and marketing strategist. Create compelling, data-driven sales collateral that addresses customer pain points, builds trust, and drives conversions. Be specific with metrics and examples.",
        "seo": "You are an expert SEO content writer specializing in local Australian businesses. Write engaging, keyword-rich content that ranks well in search engines while providing genuine value to readers. Include specific local references and actionable advice.",
        "email": "You are an expert email marketing copywriter. Write clear, compelling emails that drive action. Use conversational tone, focus on benefits, include clear CTAs, and keep emails scannable with short paragraphs."
    }

    system_prompt = system_prompts.get(task_type, "You are a helpful assistant.")

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

    payload = {
        "model": MINIMAX_MODEL_ID,
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": task}
        ],
        "temperature": 0.7,
        "max_tokens": 3000
    }

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

            if response.status != 200:
                error_text = await response.text()
                return {
                    "id": task_id,
                    "type": task_type,
                    "status": "fail",
                    "error": f"HTTP {response.status}: {error_text[:200]}",
                    "elapsed_ms": elapsed_ms
                }

            data = await response.json()
            usage = data.get('usage', {})

            # MiniMax M2.5 returns reasoning model output
            # Try content first, then reasoning, then reasoning_details
            message = data['choices'][0]['message']
            result_text = message.get('content', '')

            # If content is empty, extract from reasoning or reasoning_details
            if not result_text.strip():
                result_text = message.get('reasoning', '')

            if not result_text.strip() and 'reasoning_details' in message:
                reasoning_details = message['reasoning_details']
                if reasoning_details and isinstance(reasoning_details, list):
                    result_text = reasoning_details[0].get('text', '')

            return {
                "id": task_id,
                "type": task_type,
                "task": task,
                "status": "success",
                "result": result_text,
                "tokens": usage.get('total_tokens', 0),
                "cost_usd": (usage.get('total_tokens', 0) / 1_000_000) * 1.0,
                "elapsed_ms": elapsed_ms
            }

    except asyncio.TimeoutError:
        return {
            "id": task_id,
            "type": task_type,
            "status": "fail",
            "error": f"Timeout after {REQUEST_TIMEOUT_SECONDS}s",
            "elapsed_ms": REQUEST_TIMEOUT_SECONDS * 1000
        }
    except Exception as e:
        return {
            "id": task_id,
            "type": task_type,
            "status": "fail",
            "error": str(e)[:200],
            "elapsed_ms": int((time.time() - start_time) * 1000)
        }


async def execute_batch(
    tasks: List[Dict[str, Any]],
    batch_name: str,
    api_key: str
) -> List[Dict[str, Any]]:
    """Execute a batch of tasks in parallel."""
    print(f"\n{'='*80}")
    print(f"BATCH: {batch_name}")
    print(f"{'='*80}")

    results = []
    total = len(tasks)

    async with aiohttp.ClientSession() as session:
        for i in range(0, total, BATCH_SIZE):
            chunk = tasks[i:i + BATCH_SIZE]
            chunk_num = (i // BATCH_SIZE) + 1
            total_chunks = (total + BATCH_SIZE - 1) // BATCH_SIZE

            print(f"  Chunk {chunk_num}/{total_chunks}: Processing {len(chunk)} tasks...")

            chunk_results = await asyncio.gather(
                *[execute_agent(session, task, api_key) for task in chunk]
            )

            results.extend(chunk_results)

            successes = len([r for r in chunk_results if r["status"] == "success"])
            failures = len([r for r in chunk_results if r["status"] == "fail"])
            print(f"    ✅ {successes} success, ❌ {failures} failed")

            # Small delay between chunks
            if i + BATCH_SIZE < total:
                await asyncio.sleep(2)

    return results


def save_results(results: List[Dict[str, Any]], batch_name: str, batch_dir: str):
    """Save results to individual files."""
    os.makedirs(batch_dir, exist_ok=True)

    for result in results:
        if result["status"] == "success":
            filename = f"{result['id']:03d}_{result['type']}.md"
            filepath = os.path.join(batch_dir, filename)

            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(f"# Task {result['id']}: {result['type'].upper()}\n\n")
                f.write(f"**Prompt:** {result['task']}\n\n")
                f.write(f"**Tokens:** {result['tokens']}\n")
                f.write(f"**Cost:** ${result['cost_usd']:.4f}\n")
                f.write(f"**Time:** {result['elapsed_ms']}ms\n\n")
                f.write("---\n\n")
                f.write(result['result'])
        else:
            filename = f"{result['id']:03d}_FAILED.txt"
            filepath = os.path.join(batch_dir, filename)

            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(f"FAILED: {result.get('error', 'Unknown error')}\n")

    # Save summary
    summary_file = os.path.join(batch_dir, "_summary.json")
    with open(summary_file, 'w', encoding='utf-8') as f:
        json.dump({
            "batch": batch_name,
            "total": len(results),
            "successes": len([r for r in results if r["status"] == "success"]),
            "failures": len([r for r in results if r["status"] == "fail"]),
            "total_tokens": sum(r.get("tokens", 0) for r in results),
            "total_cost": sum(r.get("cost_usd", 0) for r in results),
            "results": results
        }, f, indent=2)

    print(f"  Results saved to: {batch_dir}")


async def main():
    """Main orchestrator."""
    print(f"\n{'='*80}")
    print("GENESIS SESSION 23 CONTENT SWARM")
    print("200 AGENTS - GPT-3.5-TURBO VIA OPENROUTER")
    print(f"{'='*80}")
    print(f"Timestamp: {datetime.now().isoformat()}")
    print(f"Model: {MINIMAX_MODEL_ID}")
    print(f"Batch Size: {BATCH_SIZE}")
    print(f"Total Tasks: {len(ALL_TASKS)}")
    print(f"{'='*80}\n")

    api_key = load_api_key()
    print(f"✅ OpenRouter API key loaded\n")

    # Execute all batches
    batch_1_results = await execute_batch(BATCH_1_TASKS, "Batch 1: Product Testing Scripts", api_key)
    save_results(batch_1_results, "Batch 1", os.path.join(OUTPUT_DIR, "batch1_tests"))

    batch_2_results = await execute_batch(BATCH_2_TASKS, "Batch 2: Sales Collateral", api_key)
    save_results(batch_2_results, "Batch 2", os.path.join(OUTPUT_DIR, "batch2_sales"))

    batch_3_results = await execute_batch(BATCH_3_TASKS, "Batch 3: SEO Content", api_key)
    save_results(batch_3_results, "Batch 3", os.path.join(OUTPUT_DIR, "batch3_seo"))

    batch_4_results = await execute_batch(BATCH_4_TASKS, "Batch 4: Email Templates", api_key)
    save_results(batch_4_results, "Batch 4", os.path.join(OUTPUT_DIR, "batch4_emails"))

    # Generate final report
    all_results = batch_1_results + batch_2_results + batch_3_results + batch_4_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"])
    total_tokens = sum(r.get("tokens", 0) for r in all_results)
    total_cost = sum(r.get("cost_usd", 0) for r in all_results)
    avg_time = sum(r.get("elapsed_ms", 0) for r in all_results) / len(all_results)

    print(f"\n{'='*80}")
    print("SWARM EXECUTION COMPLETE")
    print(f"{'='*80}")
    print(f"Total Agents: {len(all_results)}")
    print(f"Successes: {total_successes} ({total_successes/len(all_results)*100:.1f}%)")
    print(f"Failures: {total_failures}")
    print(f"Total Tokens: {total_tokens:,}")
    print(f"Total Cost: ${total_cost:.4f}")
    print(f"Average Time: {avg_time:.0f}ms")
    print(f"\nOutput Directory: {OUTPUT_DIR}")
    print(f"{'='*80}\n")


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