#!/usr/bin/env python3
"""
Genesis Session 23: 200-Agent OpenRouter Swarm
Batch 1: 100 cold email sequences for Australian agency partners
Batch 2: 100 SEO-optimized landing page content for domain portfolio

Uses MiniMax M2.5 via OpenRouter (~$0.01-0.02 per agent)
"""

import sys
sys.path.insert(0, '/mnt/e/genesis-system')

import os
import json
import time
import logging
from itertools import product as iterproduct

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s'
)
logger = logging.getLogger(__name__)

from core.multi_model_swarm import MultiModelSwarm, SWARM_MODELS

# ============================================================================
# BATCH 1: Cold Email Sequences for Australian Agency Partners (100 agents)
# ============================================================================

AGENCY_TYPES = [
    "web design agency",
    "digital marketing agency",
    "SEO agency",
    "social media marketing agency",
    "real estate marketing agency",
    "dental practice marketing agency",
    "legal firm marketing agency",
    "beauty & wellness marketing agency",
    "trades & home services marketing agency",
    "property management marketing agency",
    "medical & healthcare marketing agency",
]

EMAIL_TYPES = [
    ("intro", "Write a compelling cold email introducing the Sunaiva Talking Widget partnership opportunity"),
    ("follow_up_1", "Write a follow-up email (sent 3 days after intro with no reply) that adds urgency and social proof"),
    ("follow_up_2", "Write a second follow-up email (sent 7 days after intro) with a different angle focusing on client retention"),
    ("case_study", "Write a case study email showing how a similar agency added $5K-15K/mo in recurring revenue with AI voice widgets"),
    ("partnership_proposal", "Write a formal partnership proposal email with commission structure and onboarding details"),
    ("roi_calculator", "Write an email that walks the agency owner through the ROI math of adding AI voice widgets to their service stack"),
    ("objection_handler", "Write an email addressing common objections: 'my clients won't want AI', 'too expensive', 'already have chatbots'"),
    ("breakup", "Write a professional breakup email (last in sequence) that creates FOMO about the limited partner program"),
    ("referral_ask", "Write an email asking existing partners to refer other agency owners for bonus commission"),
]

BATCH1_SYSTEM_PROMPT = """You are an expert B2B cold email copywriter specializing in Australian agency partnerships.

PRODUCT: Sunaiva Talking Widget - AI Voice Agent that lives on websites, answers calls, books appointments, and qualifies leads 24/7.

PRICING (agency partner rates):
- Essentials: $197/mo per client widget (agency buys at wholesale)
- Business: $397/mo per client widget
- Growth: $597/mo per client widget

AGENCY COMMISSION: 20-33% recurring lifetime commission on every client they bring.
- 1-5 clients: 20% recurring
- 6-15 clients: 25% recurring
- 16+ clients: 33% recurring

Example: Agency sells 20 widgets at Business tier ($397/mo each) = $7,940/mo revenue. At 33% commission = $2,620/mo PASSIVE recurring income for the agency.

BRAND VOICE:
- Professional but conversational Australian English
- Data-driven, ROI-focused
- No hype, no BS — agencies see through that
- Focus on revenue impact and client retention
- Use "mate" sparingly and naturally, not forced

TARGET AUDIENCE: Australian agency owners/directors who serve SMBs.

OUTPUT FORMAT:
- Subject line (with A/B variant)
- Preview text (first 90 chars seen in inbox)
- Email body (150-250 words max)
- CTA (clear, single action)
- P.S. line (optional but recommended)

Keep emails SHORT. Agency owners are busy. Every sentence must earn its place."""

def generate_batch1_tasks():
    """Generate 100 cold email agent tasks."""
    tasks = []
    agent_num = 0

    # Generate combinations: 11 agency types x 9 email types = 99, plus 1 master summary
    for agency_type in AGENCY_TYPES:
        for email_key, email_instruction in EMAIL_TYPES:
            agent_num += 1
            if agent_num > 99:
                break

            task_prompt = f"""AGENCY TYPE: {agency_type}
EMAIL TYPE: {email_key}

{email_instruction} specifically tailored for an Australian {agency_type} owner.

Include:
1. Subject line + A/B variant
2. Preview text (90 chars)
3. Email body (150-250 words)
4. CTA
5. P.S. line

Make it specific to the {agency_type} vertical — reference their typical clients, pain points, and how AI voice widgets solve problems their clients actually have.

The email should feel like it was written by someone who deeply understands the {agency_type} business model."""

            tasks.append({
                'task': task_prompt,
                'model': 'openrouter-minimax',
                'system_prompt': BATCH1_SYSTEM_PROMPT,
                'agent_id': f'B1-{agent_num:03d}-{email_key}-{agency_type.split()[0]}',
                'label': f'Cold email: {email_key} for {agency_type}'
            })
        if agent_num >= 99:
            break

    # Agent 100: Master compilation instructions
    tasks.append({
        'task': """Create a MASTER EMAIL SEQUENCE PLAYBOOK that outlines:

1. The ideal 8-email sequence flow (timing between each email)
2. Best practices for Australian agency cold outreach
3. Subject line formulas that get 40%+ open rates
4. Personalization tokens to use ({{agency_name}}, {{first_name}}, {{city}}, {{client_count}})
5. Recommended sending schedule (day of week, time of day AEST)
6. Compliance notes for Australian Spam Act 2003
7. How to segment agencies by vertical for maximum relevance
8. KPIs to track: open rate, reply rate, meeting booked rate, close rate
9. Follow-up cadence after positive replies
10. Integration with Instantly.ai for automated sequences

Format as a complete playbook an agency sales rep could follow.""",
        'model': 'openrouter-minimax',
        'system_prompt': BATCH1_SYSTEM_PROMPT,
        'agent_id': 'B1-100-master-playbook',
        'label': 'Master email sequence playbook'
    })

    return tasks[:100]

# ============================================================================
# BATCH 2: SEO Landing Page Content for Domain Portfolio (100 agents)
# ============================================================================

CITY_CHATBOT_DOMAINS = [
    ("sydneychatbot.com.au", "Sydney", "NSW"),
    ("brisbanechatbot.com.au", "Brisbane", "QLD"),
    ("melbournechatbot.com.au", "Melbourne", "VIC"),
    ("adelaidechatbot.com.au", "Adelaide", "SA"),
    ("cairnschatbot.com.au", "Cairns", "QLD"),
    ("perthchatbot.com.au", "Perth", "WA"),
    ("goldcoastchatbot.com.au", "Gold Coast", "QLD"),
    ("canberrachatbot.com.au", "Canberra", "ACT"),
    ("hobartchatbot.com.au", "Hobart", "TAS"),
    ("darwinchatbot.com.au", "Darwin", "NT"),
    ("newcastlechatbot.com.au", "Newcastle", "NSW"),
    ("wollongongchatbot.com.au", "Wollongong", "NSW"),
    ("geelongchatbot.com.au", "Geelong", "VIC"),
    ("townsvillechatbot.com.au", "Townsville", "QLD"),
    ("sunshinecoastchatbot.com.au", "Sunshine Coast", "QLD"),
]

TRADE_BOT_DOMAINS = [
    ("electricianchatbot.com.au", "electrician", "electrical services"),
    ("plumberchatbot.com.au", "plumber", "plumbing services"),
    ("hvacchatbot.com.au", "HVAC technician", "heating, ventilation and air conditioning"),
    ("solarchatbot.com.au", "solar installer", "solar panel installation"),
    ("mechanicchatbot.com.au", "mechanic", "auto repair and mechanical services"),
    ("locksmithchatbot.com.au", "locksmith", "locksmith and security services"),
    ("rooferchatbot.com.au", "roofer", "roofing and roof repair"),
    ("painterchatbot.com.au", "painter", "house painting and decorating"),
    ("landscaperchatbot.com.au", "landscaper", "landscaping and garden services"),
    ("builderchatbot.com.au", "builder", "home building and renovation"),
]

INDUSTRY_BOT_DOMAINS = [
    ("dentalchatbot.com.au", "dental practice", "dental clinics and dentists"),
    ("legalchatbot.com.au", "law firm", "legal services and solicitors"),
    ("beautychatbot.com.au", "beauty salon", "beauty and wellness services"),
    ("propertychatbot.com.au", "real estate agency", "property sales and management"),
    ("clinicchatbot.com.au", "medical clinic", "healthcare clinics and GP practices"),
    ("vetcrianchatbot.com.au", "veterinary clinic", "vet and animal care services"),
    ("accountantchatbot.com.au", "accounting firm", "accounting and tax services"),
    ("fitnesschatbot.com.au", "gym and fitness centre", "fitness and personal training"),
    ("restaurantchatbot.com.au", "restaurant", "restaurant and hospitality"),
    ("hotelchatbot.com.au", "hotel and accommodation", "hospitality and accommodation"),
]

VOICE_RECEPTIONIST_DOMAINS = [
    ("aireceptionist.com.au", "AI receptionist", "businesses needing 24/7 phone answering"),
    ("voicebot.com.au", "AI voice bot", "businesses wanting automated voice interaction"),
    ("smartreceptionist.com.au", "smart AI receptionist", "SMBs upgrading from human receptionists"),
    ("afterhoursai.com.au", "after-hours AI agent", "businesses missing calls outside business hours"),
    ("callbotai.com.au", "AI call bot", "businesses automating inbound and outbound calls"),
]

BATCH2_SYSTEM_PROMPT = """You are an expert SEO content writer and conversion rate optimizer specializing in Australian local business websites.

PRODUCT: Sunaiva Talking Widget / AI Receptionist — an AI-powered voice agent that:
- Lives on business websites and answers visitor questions via voice
- Answers phone calls 24/7 (no missed calls ever)
- Books appointments directly into calendars
- Qualifies leads and captures contact details
- Speaks naturally with Australian accent options
- Costs a fraction of a human receptionist ($197-597/mo vs $3,000-5,000/mo)

PRICING:
- Essentials: $197/mo (1 widget, basic features)
- Business: $397/mo (advanced features, CRM integration)
- Growth: $597/mo (multi-location, priority support, analytics)
- ~~Real value: $997/mo~~ (always show crossed-out anchor price)

TARGET: Australian SMB owners searching for chatbot/AI solutions for their specific industry or city.

SEO REQUIREMENTS:
- Primary keyword in H1, meta title, first paragraph
- 3-5 secondary/LSI keywords naturally woven in
- Local city/state mentions for geo-targeting
- Schema markup suggestions (LocalBusiness, Product, FAQ)
- Internal linking placeholders
- 1,500-2,000 words for main content
- FAQ section with 5-7 questions (great for featured snippets)

CONVERSION ELEMENTS:
- Clear hero section with CTA
- Social proof section (stats, testimonials framework)
- Problem-agitate-solve structure
- Pricing comparison vs human receptionist
- Risk reversal (14-day free trial, no lock-in contracts)
- Multiple CTAs throughout the page

Write in natural Australian English. No American spellings."""

def generate_batch2_tasks():
    """Generate 100 SEO landing page agent tasks."""
    tasks = []
    agent_num = 0

    # City chatbot domains (15 x 2 content types = 30)
    for domain, city, state in CITY_CHATBOT_DOMAINS:
        agent_num += 1
        tasks.append({
            'task': f"""Create a complete SEO-optimized landing page for: {domain}

TARGET KEYWORD: "{city} chatbot" and "{city} AI chatbot"
SECONDARY KEYWORDS: "{city} business chatbot", "AI receptionist {city}", "chatbot for {city} businesses", "{city} website chatbot"

Write the full landing page content including:
1. Meta title (60 chars max) and meta description (155 chars max)
2. H1 headline with primary keyword
3. Hero section (problem + solution + CTA)
4. "Why {city} Businesses Choose AI Chatbots" section
5. Features section tailored to {city}/{state} businesses
6. Pricing comparison: AI chatbot vs human receptionist in {city}
7. How it works (3-step process)
8. Industry examples relevant to {city} (reference local industries)
9. FAQ section (5-7 questions targeting long-tail keywords)
10. Final CTA section
11. Schema markup suggestions

Reference local {city} landmarks, business districts, and economic context to make it genuinely local.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-city-{city.lower().replace(" ", "")}',
            'label': f'Landing page: {domain}'
        })

        # Second variant: blog-style content for the same city
        agent_num += 1
        tasks.append({
            'task': f"""Write an SEO blog article for {domain}: "The Complete Guide to AI Chatbots for {city} Businesses in 2026"

TARGET KEYWORD: "{city} AI chatbot guide"
SECONDARY: "best chatbot {city}", "{city} business automation", "AI for {city} SMBs"

Structure:
1. Introduction: Why {city} businesses are adopting AI chatbots in 2026
2. What is an AI chatbot (explained for non-technical {city} business owners)
3. Top 5 use cases for {city} businesses (industry-specific)
4. Cost analysis: AI chatbot vs hiring staff in {city} (use real {state} wage data)
5. How to choose the right AI chatbot for your {city} business
6. Implementation guide (step by step)
7. Local success metrics and ROI expectations
8. Common mistakes {city} businesses make with chatbots
9. FAQ section (5 questions)
10. Conclusion with CTA

1,500-2,000 words. Informational intent with soft sell. Include internal link placeholders.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-blog-{city.lower().replace(" ", "")}',
            'label': f'Blog: AI chatbot guide for {city}'
        })

    # Trade bot domains (10 x 2 = 20)
    for domain, trade, description in TRADE_BOT_DOMAINS:
        agent_num += 1
        tasks.append({
            'task': f"""Create a complete SEO-optimized landing page for: {domain}

TARGET KEYWORD: "{trade} chatbot" and "AI chatbot for {trade}s"
SECONDARY: "{trade} AI receptionist", "{trade} booking bot", "automated {trade} answering service", "{description} chatbot"

Write full landing page content:
1. Meta title + description
2. H1 with primary keyword
3. Hero: "Never Miss a {trade.title()} Job Again — AI That Answers Every Call"
4. Pain points section (specific to {trade}s: missed calls while on jobs, after-hours emergencies, quote requests piling up)
5. Solution section: How the AI chatbot handles {description}
6. Feature breakdown for {trade} businesses:
   - Emergency call triaging
   - Quote request capture
   - Appointment booking
   - After-hours answering
   - Lead qualification
7. Pricing vs human receptionist (use Australian {trade} rates: avg $25-35/hr receptionist)
8. Testimonial framework (realistic {trade} business owner quotes)
9. FAQ (5-7 {trade}-specific questions)
10. CTA: "Get Your {trade.title()} AI Receptionist — 14-Day Free Trial"
11. Schema markup

Make it sound like it was written BY someone who understands the {trade} trade.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-trade-{trade.lower().replace(" ", "")}',
            'label': f'Landing page: {domain}'
        })

        agent_num += 1
        tasks.append({
            'task': f"""Write an SEO article for {domain}: "How Australian {trade.title()}s Are Using AI to Never Miss a Call Again"

TARGET KEYWORD: "AI for {trade}s Australia"
Structure:
1. The $50,000 problem: How many jobs {trade}s lose to missed calls annually
2. Why traditional answering services fail {trade}s
3. What an AI chatbot does differently for {description}
4. Real-world scenario walkthroughs (emergency call at 2am, quote request during a job, etc.)
5. Cost comparison: AI vs human vs voicemail
6. Setup guide: Get running in 15 minutes
7. ROI calculator breakdown
8. FAQ (5 questions)

1,200-1,500 words. Practical, no-BS tone that resonates with tradies.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-tradearticle-{trade.lower().replace(" ", "")}',
            'label': f'Article: AI for {trade}s'
        })

    # Industry bot domains (10 x 2 = 20)
    for domain, industry, description in INDUSTRY_BOT_DOMAINS:
        agent_num += 1
        tasks.append({
            'task': f"""Create an SEO-optimized landing page for: {domain}

TARGET KEYWORD: "{industry} chatbot" and "AI chatbot for {industry}"
SECONDARY: "{industry} AI receptionist", "{description} chatbot", "automated {industry} booking"

Write full landing page:
1. Meta title + description
2. H1 targeting primary keyword
3. Hero section: "{industry.title()} AI That Never Sleeps"
4. Pain points for {industry} owners (missed appointments, after-hours calls, staff overwhelm)
5. Solution: How AI handles {description}
6. Industry-specific features:
   - Appointment scheduling
   - Patient/client intake
   - FAQ handling
   - Emergency triage
   - Follow-up automation
7. Compliance notes relevant to {industry} (privacy, professional standards)
8. Pricing comparison
9. Implementation timeline
10. FAQ (5-7 industry-specific questions)
11. CTA + schema markup suggestions

Deeply tailored to the {industry} vertical. Reference Australian {industry} standards and practices.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-industry-{industry.lower().replace(" ", "")}',
            'label': f'Landing page: {domain}'
        })

        agent_num += 1
        tasks.append({
            'task': f"""Write an SEO article for {domain}: "Why Every Australian {industry.title()} Needs an AI Receptionist in 2026"

TARGET KEYWORD: "AI receptionist {industry} Australia"
Structure:
1. The staffing crisis in Australian {description}
2. What patients/clients actually want (24/7 access, instant responses)
3. How AI receptionists work for {industry} operations
4. Privacy and compliance in {description} (Australian regulations)
5. ROI analysis for a typical Australian {industry}
6. Case study framework
7. Getting started guide
8. FAQ (5 questions)

1,200-1,500 words. Professional tone appropriate for {industry} owners.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-industryarticle-{industry.lower().replace(" ", "")}',
            'label': f'Article: AI for {industry}'
        })

    # Voice/receptionist domains (5 x 2 = 10)
    for domain, product_type, target_audience in VOICE_RECEPTIONIST_DOMAINS:
        agent_num += 1
        tasks.append({
            'task': f"""Create an SEO-optimized landing page for: {domain}

TARGET KEYWORD: "{product_type}" and "{product_type} Australia"
SECONDARY: "best {product_type}", "{product_type} for small business", "Australian {product_type}"

Write a comprehensive landing page:
1. Meta title + description optimized for "{product_type}"
2. H1 + hero section
3. Problem: {target_audience} losing revenue to missed calls/slow responses
4. Solution: How {product_type} technology works
5. Feature comparison matrix (vs human receptionist, vs basic IVR, vs chatbot-only)
6. Pricing tiers: Essentials $197 / Business $397 / Growth $597 (~~$997~~ crossed out)
7. Industry use cases (3-4 verticals)
8. Technology explainer (natural voice AI, not robotic)
9. Integration list (calendar, CRM, phone system)
10. Trust signals (uptime SLA, Australian data, support hours)
11. FAQ section (7 questions)
12. Final CTA + schema markup

This is a category-defining page — make it the definitive resource for "{product_type}" in Australia.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-voice-{domain.split(".")[0]}',
            'label': f'Landing page: {domain}'
        })

        agent_num += 1
        tasks.append({
            'task': f"""Write a comparison/buyer's guide article for {domain}: "Best {product_type.title()} Solutions in Australia — 2026 Buyer's Guide"

TARGET: "best {product_type} Australia 2026"
Structure:
1. What to look for in a {product_type}
2. Top features checklist (voice quality, language, integration, pricing, support)
3. Cost analysis: what {target_audience} should budget
4. How Sunaiva compares (position as premium-quality, fair-price option)
5. Implementation checklist
6. Red flags to avoid in {product_type} providers
7. FAQ (5 questions)

1,500 words. Buyer's guide format. Position Sunaiva as the recommended choice without being too salesy.""",
            'model': 'openrouter-minimax',
            'system_prompt': BATCH2_SYSTEM_PROMPT,
            'agent_id': f'B2-{agent_num:03d}-guide-{domain.split(".")[0]}',
            'label': f'Buyer guide: {domain}'
        })

    return tasks[:100]


def main():
    """Fire the 200-agent swarm."""
    print("=" * 80)
    print("GENESIS SESSION 23: 200-AGENT OPENROUTER SWARM")
    print("=" * 80)
    print()

    # Initialize swarm
    swarm = MultiModelSwarm()

    if 'openrouter-minimax' not in swarm.available_models:
        print("FATAL: openrouter-minimax (MiniMax M2.5 via OpenRouter) not available!")
        print(f"Available models: {swarm.available_models}")
        print("Set OPENROUTER_API_KEY in .env")
        sys.exit(1)

    print(f"Available models: {swarm.available_models}")
    print(f"Using: MiniMax M2.5 via OpenRouter")
    print()

    # Generate tasks
    batch1_tasks = generate_batch1_tasks()
    batch2_tasks = generate_batch2_tasks()

    print(f"Batch 1 (Cold Emails): {len(batch1_tasks)} agents")
    print(f"Batch 2 (Landing Pages): {len(batch2_tasks)} agents")
    print(f"Total: {len(batch1_tasks) + len(batch2_tasks)} agents")
    print()

    # ---- BATCH 1: Cold Emails ----
    print("=" * 80)
    print("BATCH 1: Firing 100 Cold Email Agents...")
    print("=" * 80)

    batch1_start = time.time()
    batch1_results = swarm.parallel_execute(
        tasks=batch1_tasks,
        default_model='openrouter-minimax',
        max_workers=25  # 25 concurrent threads to stay within rate limits
    )
    batch1_elapsed = time.time() - batch1_start

    # Save batch 1
    batch1_summary = swarm.save_results(
        batch1_results,
        '/mnt/e/genesis-system/swarm-output/session23/batch1-cold-emails'
    )

    batch1_success = sum(1 for r in batch1_results if r['status'] == 'success')
    batch1_cost = sum(
        r.get('cost', 0) for r in batch1_results if r.get('cost')
    )

    print(f"\nBatch 1 Complete: {batch1_success}/{len(batch1_results)} succeeded in {batch1_elapsed:.1f}s")
    print(f"Summary: {batch1_summary}")
    print()

    # ---- BATCH 2: Landing Pages ----
    print("=" * 80)
    print("BATCH 2: Firing 100 Landing Page Agents...")
    print("=" * 80)

    batch2_start = time.time()
    batch2_results = swarm.parallel_execute(
        tasks=batch2_tasks,
        default_model='openrouter-minimax',
        max_workers=25
    )
    batch2_elapsed = time.time() - batch2_start

    # Save batch 2
    batch2_summary = swarm.save_results(
        batch2_results,
        '/mnt/e/genesis-system/swarm-output/session23/batch2-landing-pages'
    )

    batch2_success = sum(1 for r in batch2_results if r['status'] == 'success')

    print(f"\nBatch 2 Complete: {batch2_success}/{len(batch2_results)} succeeded in {batch2_elapsed:.1f}s")
    print(f"Summary: {batch2_summary}")
    print()

    # ---- FINAL REPORT ----
    total_success = batch1_success + batch2_success
    total_agents = len(batch1_results) + len(batch2_results)
    total_elapsed = batch1_elapsed + batch2_elapsed

    print("=" * 80)
    print("FINAL SWARM REPORT")
    print("=" * 80)
    print(f"Total Agents:    {total_agents}")
    print(f"Succeeded:       {total_success}")
    print(f"Failed:          {total_agents - total_success}")
    print(f"Success Rate:    {(total_success/total_agents*100):.1f}%")
    print(f"Total Time:      {total_elapsed:.1f}s ({total_elapsed/60:.1f} min)")
    print(f"Avg per Agent:   {total_elapsed/total_agents:.2f}s")
    print(f"Est. Cost:       ~${total_agents * 0.015:.2f} (at ~$0.015/agent)")
    print()
    print(f"Batch 1 Output:  /mnt/e/genesis-system/swarm-output/session23/batch1-cold-emails/")
    print(f"Batch 2 Output:  /mnt/e/genesis-system/swarm-output/session23/batch2-landing-pages/")
    print("=" * 80)

    # Write master report
    report = {
        "session": 23,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
        "total_agents": total_agents,
        "total_success": total_success,
        "total_failed": total_agents - total_success,
        "success_rate": f"{(total_success/total_agents*100):.1f}%",
        "total_time_seconds": round(total_elapsed, 1),
        "model": "minimax/minimax-m2.5 via OpenRouter",
        "estimated_cost_usd": round(total_agents * 0.015, 2),
        "batch1": {
            "name": "Cold Email Sequences",
            "agents": len(batch1_results),
            "success": batch1_success,
            "time_seconds": round(batch1_elapsed, 1),
            "output_dir": "batch1-cold-emails/"
        },
        "batch2": {
            "name": "SEO Landing Pages",
            "agents": len(batch2_results),
            "success": batch2_success,
            "time_seconds": round(batch2_elapsed, 1),
            "output_dir": "batch2-landing-pages/"
        }
    }

    report_path = '/mnt/e/genesis-system/swarm-output/session23/swarm_report.json'
    with open(report_path, 'w') as f:
        json.dump(report, f, indent=2)
    print(f"\nMaster report: {report_path}")


if __name__ == "__main__":
    main()
