"""
Enterprise RFP Response Automation System - Multi-Agent Delegation with Orchestrator

This example demonstrates how to use Synq's Orchestrator + TaskDelegator to coordinate
multiple specialized agents for handling complex enterprise workflows.

Business Problem:
- Companies receive RFPs (Request for Proposals) from potential clients
- Must respond quickly with comprehensive proposals covering technical, financial, and legal aspects
- Coordinating responses across departments is time-consuming and delays sales cycles

Solution:
- 4 specialized agents working together via TaskDelegator
- Orchestrator uses LLM to intelligently route tasks to the right agents
- Automated analysis, design, pricing, and compliance checking
- Reduces response time from days to minutes

Agents:
1. Requirements Analyst - Extracts and analyzes RFP requirements
2. Technical Architect - Designs cloud migration solution
3. Pricing Analyst - Calculates costs and creates pricing proposals
4. Compliance Agent - Reviews legal terms and compliance requirements

Setup:
1. Install dependencies: pip install openai python-dotenv
2. Create a .env file with: OPENAI_API_KEY='your-key-here'
3. Run: python delegator_rfp_system.py

The script will:
- Create an Orchestrator with GPT-4o for intelligent routing
- Start all 4 agents in the background
- Process a sample RFP through the delegation pipeline with smart routing
- Generate a complete proposal with all sections
"""

import synqed
import asyncio
import os

from pathlib import Path
from dotenv import load_dotenv
from openai import AsyncOpenAI
from synqed import Orchestrator, LLMProvider

# Load environment variables
load_dotenv()
load_dotenv(dotenv_path=Path(__file__).parent / '.env')

# ============================================================================
# SAMPLE RFP DOCUMENT
# ============================================================================

SAMPLE_RFP = """
REQUEST FOR PROPOSAL: ENTERPRISE CLOUD MIGRATION SERVICES

Company: GlobalCorp Industries Inc.
Industry: Manufacturing & Distribution
Issue Date: November 15, 2024
Response Deadline: December 1, 2024

PROJECT OVERVIEW:
GlobalCorp Industries requires a comprehensive cloud migration strategy for our legacy 
on-premises infrastructure. We operate 24/7 manufacturing facilities across 12 locations 
globally and cannot afford significant downtime.

TECHNICAL REQUIREMENTS:
- Migrate 500+ virtual machines (mix of Windows Server 2016-2022 and RHEL 7-8)
- 100TB of structured data (SQL Server, Oracle databases)
- 50TB of unstructured data (file shares, application data)
- 24/7 uptime requirement (max 2 hours maintenance window per month)
- Geographic distribution: US (60%), EU (30%), APAC (10%)
- Peak load: 50,000 concurrent users during business hours
- Integration with existing SAP ERP system

COMPLIANCE REQUIREMENTS:
- SOC 2 Type II certification required
- GDPR compliance for EU operations
- ISO 27001 aligned security controls
- Data residency requirements (EU data must stay in EU)

BUSINESS REQUIREMENTS:
- Complete migration within 12 months
- Phased approach to minimize risk
- Cost optimization vs. current $2M annual infrastructure spend
- Training for internal IT team (15 engineers)
- 24/7 support during migration and 6 months post-migration

PROPOSAL REQUIREMENTS:
1. Technical approach and architecture
2. Detailed migration timeline and phases
3. Comprehensive pricing (infrastructure + services + support)
4. Risk mitigation strategies
5. Compliance and security approach
6. Team qualifications and past experience

EVALUATION CRITERIA:
- Technical solution (35%)
- Pricing and value (30%)
- Risk mitigation (20%)
- Team experience (15%)

Budget Range: $3M-$5M total project cost
"""

# ============================================================================
# AGENT LOGIC FUNCTIONS
# ============================================================================

async def requirements_analyst_logic(context):
    """
    Analyzes RFP documents and extracts key requirements.
    Acts as the first step in the proposal pipeline.
    """
    user_message = context.get_user_input()
    
    client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
    
    system_prompt = """You are an expert Requirements Analyst specializing in enterprise RFPs.

Your role:
- Parse and understand RFP documents thoroughly
- Extract key technical, business, and compliance requirements
- Identify client pain points and priorities
- Highlight any ambiguous requirements that need clarification
- Structure requirements in a clear, actionable format

Output Format:
## Technical Requirements
- List specific technical needs

## Business Requirements
- List business objectives and constraints

## Compliance Requirements
- List regulatory and compliance needs

## Key Success Criteria
- What matters most to the client

## Risk Factors & Considerations
- Potential challenges or concerns
"""
    
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message}
        ],
        temperature=0.3
    )
    
    return response.choices[0].message.content


async def technical_architect_logic(context):
    """
    Designs technical solution and cloud architecture based on requirements.
    Creates detailed migration strategy and architecture diagrams (conceptual).
    """
    user_message = context.get_user_input()
    
    client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
    
    system_prompt = """You are a Senior Cloud Architect with 15+ years of experience in large-scale migrations.

Your role:
- Design comprehensive cloud migration architecture
- Select appropriate cloud services (compute, storage, networking, databases)
- Plan detailed migration phases and timeline
- Address technical risks with mitigation strategies
- Ensure high availability and disaster recovery
- Consider cost optimization opportunities

Output Format:
## Proposed Architecture
- High-level architecture overview
- Key cloud services and why

## Migration Strategy
- Phase 1: [timeline and scope]
- Phase 2: [timeline and scope]
- Phase 3: [timeline and scope]

## Technical Implementation
- Compute strategy
- Storage and database approach
- Network and security architecture
- Integration points (SAP, etc.)

## High Availability & DR
- Uptime strategy
- Backup and recovery approach

## Risk Mitigation
- Technical risks and how to address them
"""
    
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message}
        ],
        temperature=0.4
    )
    
    return response.choices[0].message.content


async def pricing_analyst_logic(context):
    """
    Calculates costs and creates comprehensive pricing proposals.
    Provides multiple pricing tiers and ROI analysis.
    """
    user_message = context.get_user_input()
    
    client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
    
    system_prompt = """You are a Cloud Financial Analyst specializing in enterprise pricing and TCO analysis.

Your role:
- Estimate accurate infrastructure costs
- Calculate migration effort and professional services costs
- Create transparent pricing with clear breakdowns
- Show ROI and TCO compared to current spend
- Provide pricing tiers if applicable

Output Format:
## Infrastructure Costs (Annual)
- Compute: $XXX,XXX
- Storage: $XXX,XXX
- Networking: $XXX,XXX
- Databases: $XXX,XXX
- Security & Compliance: $XXX,XXX
**Subtotal**: $XXX,XXX/year

## Migration Services (One-Time)
- Planning & Architecture: $XXX,XXX
- Migration Execution: $XXX,XXX
- Testing & Validation: $XXX,XXX
- Training: $XXX,XXX
**Subtotal**: $XXX,XXX

## Support & Maintenance
- 24/7 Support during migration: $XXX,XXX
- 6-month post-migration support: $XXX,XXX

## Total Investment
- Year 1: $XXX,XXX (migration + infrastructure)
- Year 2-3: $XXX,XXX/year (infrastructure + support)

## ROI Analysis
- Current annual spend: $2M
- Projected annual spend: $X.XM
- Annual savings: $XXX,XXX
- Payback period: XX months
- 3-year TCO comparison

## Cost Optimization Opportunities
- List potential cost savings
"""
    
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message}
        ],
        temperature=0.3
    )
    
    return response.choices[0].message.content


async def compliance_agent_logic(context):
    """
    Reviews legal terms and compliance requirements.
    Identifies compliance gaps and provides remediation strategies.
    """
    user_message = context.get_user_input()
    
    client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
    
    system_prompt = """You are a Cloud Compliance and Legal Specialist with expertise in enterprise regulations.

Your role:
- Review RFP terms and conditions
- Identify all compliance requirements (GDPR, SOC2, ISO 27001, etc.)
- Assess data residency and sovereignty requirements
- Flag potential legal risks or concerns
- Provide compliance implementation strategy

Output Format:
## Compliance Requirements Summary
- List all regulatory requirements from RFP

## Compliance Approach
### SOC 2 Type II
- How we meet this requirement

### GDPR
- Data residency strategy
- Privacy controls

### ISO 27001
- Security controls alignment

### Industry-Specific
- Any other compliance needs

## Data Governance
- Data classification strategy
- Data residency implementation
- Data protection measures

## Legal Considerations
- Contract terms review
- Liability and SLA commitments
- Any red flags or concerns

## Compliance Timeline
- Compliance milestones during migration
- Ongoing compliance monitoring
"""
    
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message}
        ],
        temperature=0.3
    )
    
    return response.choices[0].message.content


# ============================================================================
# MAIN DELEGATION WORKFLOW
# ============================================================================

async def main():
    """
    Main workflow demonstrating enterprise multi-agent delegation with orchestrator.
    """
    print("=" * 80)
    print("ENTERPRISE RFP RESPONSE AUTOMATION SYSTEM")
    print("Multi-Agent Delegation with Synq Orchestrator + TaskDelegator")
    print("=" * 80)
    print()
    
    # Check for API key
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("❌ Error: OPENAI_API_KEY not found in environment")
        print("Please create a .env file with: OPENAI_API_KEY='your-key-here'")
        return
    print(f"✓ API key found")
    print()
    
    # ========================================================================
    # STEP 1: CREATE SPECIALIZED AGENTS
    # ========================================================================
    print("📋 Step 1: Creating specialized agents...")
    print()
    
    # Agent 1: Requirements Analyst
    requirements_agent = synqed.Agent(
        name="Requirements Analyst",
        description="Analyzes RFP documents and extracts key technical, business, and compliance requirements",
        skills=["requirements_analysis", "document_parsing", "client_needs_assessment", "rfp_analysis"],
        executor=requirements_analyst_logic,
        capabilities={
            "streaming": False,  # Complete analysis at once
            "push_notifications": False,
            "state_transition_history": False
        }
    )
    
    # Agent 2: Technical Architect
    technical_agent = synqed.Agent(
        name="Technical Architect",
        description="Designs cloud migration solutions and technical architecture for enterprise infrastructure",
        skills=["solution_design", "cloud_architecture", "migration_planning", "technical_writing"],
        executor=technical_architect_logic,
        capabilities={
            "streaming": False,
            "push_notifications": False,
            "state_transition_history": False
        }
    )
    
    # Agent 3: Pricing Analyst
    pricing_agent = synqed.Agent(
        name="Pricing Analyst",
        description="Calculates costs, creates pricing proposals, and performs ROI analysis for cloud solutions",
        skills=["cost_estimation", "pricing_strategy", "financial_analysis", "roi_calculation"],
        executor=pricing_analyst_logic,
        capabilities={
            "streaming": False,
            "push_notifications": False,
            "state_transition_history": False
        }
    )
    
    # Agent 4: Compliance Agent
    compliance_agent = synqed.Agent(
        name="Compliance Agent",
        description="Reviews legal terms and ensures compliance with regulatory requirements (GDPR, SOC2, ISO 27001)",
        skills=["legal_review", "compliance_check", "risk_assessment", "regulatory_analysis"],
        executor=compliance_agent_logic,
        capabilities={
            "streaming": False,
            "push_notifications": False,
            "state_transition_history": False
        }
    )
    
    print("✓ Requirements Analyst created")
    print("✓ Technical Architect created")
    print("✓ Pricing Analyst created")
    print("✓ Compliance Agent created")
    print()
    
    # ========================================================================
    # STEP 2: START AGENT SERVERS IN BACKGROUND
    # ========================================================================
    print("🚀 Step 2: Starting agent servers...")
    print()
    
    # Start servers on different ports
    requirements_server = synqed.AgentServer(requirements_agent, port=8001)
    technical_server = synqed.AgentServer(technical_agent, port=8002)
    pricing_server = synqed.AgentServer(pricing_agent, port=8003)
    compliance_server = synqed.AgentServer(compliance_agent, port=8004)
    
    # Start all servers in background
    await requirements_server.start_background()
    await technical_server.start_background()
    await pricing_server.start_background()
    await compliance_server.start_background()
    
    print(f"✓ Requirements Analyst running at {requirements_agent.url}")
    print(f"✓ Technical Architect running at {technical_agent.url}")
    print(f"✓ Pricing Analyst running at {pricing_agent.url}")
    print(f"✓ Compliance Agent running at {compliance_agent.url}")
    print()
    
    # Give servers a moment to fully start
    await asyncio.sleep(2)
    
    # ========================================================================
    # STEP 3: CREATE ORCHESTRATOR FOR INTELLIGENT ROUTING
    # ========================================================================
    print("🧠 Step 3: Setting up Orchestrator for intelligent routing...")
    print()
    
    # Create orchestrator with GPT-4o for smart agent selection
    orchestrator = Orchestrator(
        provider=LLMProvider.OPENAI,
        api_key=api_key,
        model="gpt-4o",
        temperature=0.3,  # Lower temperature for consistent routing
    )
    
    print("✓ Orchestrator created with GPT-4o")
    print("  The orchestrator will analyze each task and select the best agent")
    print()
    
    # ========================================================================
    # STEP 4: SET UP TASK DELEGATOR WITH ORCHESTRATOR
    # ========================================================================
    print("🎯 Step 4: Setting up TaskDelegator with Orchestrator...")
    print()
    
    # Create delegator with orchestrator
    delegator = synqed.TaskDelegator(orchestrator=orchestrator)
    
    # Register all agents (automatically registers with orchestrator too)
    delegator.register_agent(agent=requirements_agent)
    delegator.register_agent(agent=technical_agent)
    delegator.register_agent(agent=pricing_agent)
    delegator.register_agent(agent=compliance_agent)
    
    # List registered agents
    agents_info = delegator.list_agents()
    print(f"✓ Registered {len(agents_info)} agents:")
    for agent_info in agents_info:
        print(f"  - {agent_info['name']}: {', '.join(agent_info['skills'])}")
    print()
    
    # ========================================================================
    # STEP 5: PROCESS RFP THROUGH DELEGATION PIPELINE WITH SMART ROUTING
    # ========================================================================
    print("=" * 80)
    print("PROCESSING RFP: GlobalCorp Industries Cloud Migration")
    print("=" * 80)
    print()
    
    # Phase 1: Requirements Analysis (Orchestrator selects the agent)
    print("🔍 Phase 1: Requirements Analysis")
    print("-" * 80)
    print("🤖 Orchestrator analyzing task and selecting agent...")
    print()
    
    requirements_result = await delegator.submit_task(
        task_description=f"Analyze this RFP and extract all key requirements:\n\n{SAMPLE_RFP}",
        use_orchestrator=True  # Let orchestrator choose the agent
    )
    
    print(requirements_result)
    print()
    
    # Phase 2: Parallel Processing (Technical Design + Compliance Review)
    print("⚡ Phase 2: Parallel Processing (Technical Design + Compliance Review)")
    print("-" * 80)
    print("🤖 Orchestrator routing tasks to appropriate agents in parallel...")
    print()
    
    # Create the task descriptions with context from requirements
    technical_task = f"""Based on these requirements, design a comprehensive cloud migration solution:

REQUIREMENTS:
{requirements_result}

ORIGINAL RFP CONTEXT:
{SAMPLE_RFP}
"""
    
    compliance_task = f"""Review compliance requirements and provide compliance strategy:

REQUIREMENTS:
{requirements_result}

ORIGINAL RFP:
{SAMPLE_RFP}
"""
    
    # Execute technical and compliance in parallel (orchestrator selects agents)
    technical_result, compliance_result = await asyncio.gather(
        delegator.submit_task(technical_task, use_orchestrator=True),
        delegator.submit_task(compliance_task, use_orchestrator=True)
    )
    
    print("TECHNICAL SOLUTION:")
    print("-" * 80)
    print(technical_result)
    print()
    
    print("COMPLIANCE ANALYSIS:")
    print("-" * 80)
    print(compliance_result)
    print()
    
    # Phase 3: Pricing Analysis (Sequential - needs technical solution)
    print("💰 Phase 3: Pricing Analysis")
    print("-" * 80)
    print("🤖 Orchestrator selecting agent for pricing analysis...")
    print()
    
    pricing_task = f"""Create comprehensive pricing for this solution:

REQUIREMENTS:
{requirements_result}

TECHNICAL SOLUTION:
{technical_result}

Client's current spend: $2M/year
Budget range: $3M-$5M total project cost
"""
    
    pricing_result = await delegator.submit_task(
        pricing_task,
        use_orchestrator=True  # Let orchestrator choose
    )
    
    print(pricing_result)
    print()
    
    # ========================================================================
    # STEP 6: GENERATE FINAL PROPOSAL SUMMARY
    # ========================================================================
    print("=" * 80)
    print("FINAL PROPOSAL SUMMARY")
    print("=" * 80)
    print()
    
    print("All sections completed successfully!")
    print()
    print("Proposal Sections Generated:")
    print("  1. ✓ Requirements Analysis (orchestrator selected Requirements Analyst)")
    print("  2. ✓ Technical Solution & Architecture (orchestrator selected Technical Architect)")
    print("  3. ✓ Compliance & Legal Review (orchestrator selected Compliance Agent)")
    print("  4. ✓ Pricing & Financial Analysis (orchestrator selected Pricing Analyst)")
    print()
    print("🧠 Orchestrator Intelligence:")
    print("  The orchestrator analyzed each task description and agent capabilities")
    print("  to intelligently route tasks to the most appropriate agent without")
    print("  requiring manual agent selection. This enables truly autonomous")
    print("  multi-agent workflows.")
    print()
    print("📋 Next Steps:")
    print("  - Review all sections for accuracy")
    print("  - Add executive summary")
    print("  - Include team credentials and past projects")
    print("  - Format as professional proposal document")
    print("  - Submit before December 1, 2024 deadline")
    print()
    print("⏱ Time Saved: Traditional process takes 3-5 days, this took ~2 minutes!")
    print("🎯 Automation Level: Fully autonomous with intelligent routing")
    print()
    
    # ========================================================================
    # CLEANUP
    # ========================================================================
    print("🧹 Cleaning up...")
    
    # Close all delegator clients
    await delegator.close_all()
    
    # Stop all servers
    await requirements_server.stop()
    await technical_server.stop()
    await pricing_server.stop()
    await compliance_server.stop()
    
    print("✓ All agents stopped")
    print()
    print("=" * 80)
    print("✨ RFP Response Automation Complete!")
    print("=" * 80)


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

