"""
Shared Planning Prompt Builder

Builds the rich, detailed planning prompt used by ALL strategies (Agno, Claude Code SDK, etc.)
This ensures 100% identical prompts across all implementations.
"""

import json
from typing import List
from control_plane_api.app.models.task_planning import TaskPlanRequest, AgentInfo, TeamInfo
from control_plane_api.app.lib.task_planning.helpers import REFINEMENT_INSTRUCTIONS


def build_planning_prompt(
    request: TaskPlanRequest,
    agents_to_use: List[dict],
    teams_to_use: List[dict],
    pricing_context: str,
) -> str:
    """
    Build the complete planning prompt with full context.

    This is the SAME prompt used by both Agno and Claude Code SDK to ensure
    100% identical results.

    Args:
        request: Task plan request
        agents_to_use: Prepared agents data (JSON-serializable)
        teams_to_use: Prepared teams data (JSON-serializable)
        pricing_context: Model pricing information

    Returns:
        Complete planning prompt string
    """
    # Build environments context
    environments_context = (
        "\n".join(
            [
                f"- **{e.name}** (ID: `{e.id}`)\n"
                f"  - **Type**: {e.type}\n"
                f"  - **Status**: {e.status}"
                for e in request.environments
            ]
        )
        if request.environments
        else "No execution environments specified"
    )

    # Build worker queues context
    worker_queues_context = (
        "\n".join(
            [
                f"- **{q.name}** (ID: `{q.id}`)\n"
                f"  - **Environment**: {q.environment_id or 'Not specified'}\n"
                f"  - **Active Workers**: {q.active_workers}\n"
                f"  - **Status**: {q.status}\n"
                f"  - **Capacity**: {'Available' if q.active_workers > 0 and q.status == 'active' else 'Limited or Inactive'}"
                for q in request.worker_queues
            ]
        )
        if request.worker_queues
        else "No worker queues specified"
    )

    # System capabilities
    system_capabilities = """
**Available System Capabilities:**
- **Code Execution**: Python, Bash, JavaScript, and other languages
- **Cloud Integrations**: AWS (S3, EC2, Lambda, RDS, CloudWatch), Azure, GCP
- **APIs & Tools**: REST APIs, GraphQL, Kubernetes, Docker, Terraform
- **Databases**: PostgreSQL, MySQL, MongoDB, Redis
- **Monitoring**: Datadog, Prometheus, Grafana, CloudWatch
- **Security**: IAM policies, security scanning, compliance checks
- **DevOps**: CI/CD pipelines, Infrastructure as Code, automation scripts
"""

    # Check conversation context
    has_conversation_history = bool(request.conversation_context and request.conversation_context.strip())
    should_be_decisive = request.iteration > 1 or has_conversation_history

    # Build the complete prompt
    planning_prompt = f"""
# Task Planning Request - Iteration #{request.iteration}

## Task Description
{request.description}

## Priority
{request.priority.upper()}

{"## Previous Conversation (USE THIS CONTEXT)" if has_conversation_history else ""}
{request.conversation_context if has_conversation_history else ""}

{"## User Feedback for Refinement" if request.refinement_feedback else ""}
{request.refinement_feedback if request.refinement_feedback else ""}

{"## Previous Plan (to be refined)" if request.previous_plan else ""}
{json.dumps(request.previous_plan, indent=2) if request.previous_plan else ""}

{REFINEMENT_INSTRUCTIONS.format(iteration=request.iteration) if request.previous_plan and request.refinement_feedback else ""}

## Available Resources

**IMPORTANT**: Agent and team data below is provided as complete JSON with ALL details including:
- execution_environment (secrets, env_vars, integration_ids)
- skills (with full configuration)
- projects and environments
- capabilities and runtime info

Use this rich data to make informed decisions about agent/team selection and task planning.

### Agents
{json.dumps(agents_to_use, indent=2) if agents_to_use else "No agents available"}

### Teams
{json.dumps(teams_to_use, indent=2) if teams_to_use else "No teams available"}

### Execution Environments
{environments_context}

### Worker Queues
{worker_queues_context}

{system_capabilities}

{pricing_context}

## Your Task

{'**BE DECISIVE**: You have conversation history showing the user has already provided context. DO NOT ask more questions. Use the information provided in the conversation history above to create a reasonable plan. Make sensible assumptions where needed and proceed with planning.' if should_be_decisive else '**FIRST ITERATION**: Review if you have enough context. ONLY ask questions if you are missing CRITICAL information that makes planning impossible (like completely unknown technology stack or domain). If the task is reasonably clear, proceed with planning and make reasonable assumptions.'}

{'**IMPORTANT**: DO NOT ask questions. The user wants a plan now. Use the conversation history above and create a comprehensive plan.' if should_be_decisive else 'If you need CRITICAL information to proceed, set has_questions=true and provide 1-2 critical questions in the questions array. Otherwise, proceed with planning.'}

Analyze this task and provide a comprehensive plan. **Note: The response structure is automatically enforced via output_schema - focus on content quality.**

**Important Planning Guidelines:**
1. For `recommended_execution`, choose the MOST CAPABLE entity (agent or team) based on:
   - Task complexity
   - Agent/team capabilities and model
   - Description fit
   - Whether multiple agents are needed (prefer team) or single agent is sufficient
2. The recommended entity MUST be from the available agents/teams list above
3. For `recommended_environment_id` and `recommended_worker_queue_id`:
   - Choose the BEST environment based on task requirements (production vs staging vs development)
   - Choose a worker queue with AVAILABLE CAPACITY (active_workers > 0 and status = 'active')
   - Match worker queue to the selected environment if possible
   - Provide clear `execution_reasoning` explaining your environment/queue selection
   - If no suitable queue is available, still recommend one and note the capacity concern in reasoning
4. Use IDs exactly as provided from the lists above
5. **CRITICAL - Enhanced Cost Breakdown**:
   - **Team Breakdown**: For each agent/team member, include:
     - `model_info`: Specify the model they'll use (use the model_id from agent info)
       - Estimate input/output tokens based on task complexity
       - Use realistic pricing: Claude Sonnet 4 ($0.003/1K in, $0.015/1K out), GPT-4o ($0.0025/1K in, $0.01/1K out)
       - Calculate total_model_cost accurately
     - `expected_tools`: List tools they'll use with estimated call counts
       - AWS APIs: $0.0004-0.001 per call
       - Database queries: $0.0001 per query
       - Free tools (kubectl, bash): $0.0 per call
     - `agent_cost`: Sum of model_cost + tool_costs
   - **Cost Estimate**: Provide detailed breakdown:
     - `llm_costs`: Array of LLM costs by model (aggregate from team breakdown)
     - `tool_costs`: Categorized tool costs (AWS APIs, Database Queries, External APIs)
     - `runtime_cost`: Worker execution time × cost per hour ($0.10/hr typical)
     - Ensure `estimated_cost_usd` = sum of all LLM + tool + runtime costs
     - Legacy `breakdown` still required for backwards compatibility
6. **Realistic Token Estimates**:
   - Simple tasks (story points 1-3): 2-5K input, 1-2K output tokens per agent
   - Medium tasks (story points 5-8): 5-10K input, 2-5K output tokens per agent
   - Complex tasks (story points 13-21): 10-20K input, 5-10K output tokens per agent
7. **Tool Call Estimates**:
   - Consider what APIs/tools the agent will actually use for this specific task
   - Be realistic: Simple tasks might only need 5-10 API calls total
   - Complex deployments might need 50+ API calls across multiple tools
8. **CRITICAL - Realized Savings Calculation** (keep for backwards compatibility):
   - **WITHOUT KUBIYA**: Calculate what it would cost using manual human execution
     - Break down by SPECIFIC ROLES (e.g., "Senior DevOps Engineer", "Security Engineer")
     - Use realistic hourly rates: Senior ($120-200/hr), Mid-level ($80-120/hr), Junior ($50-80/hr)
     - Calculate without_kubiya_cost = sum of all human resource costs
     - Estimate without_kubiya_hours = total time if done manually
   - **WITH KUBIYA**: Calculate AI orchestration costs and time
     - with_kubiya_cost = estimated AI execution cost (API calls, compute)
     - with_kubiya_hours = estimated time for AI agents to complete
   - **REALIZED SAVINGS**:
     - money_saved = without_kubiya_cost - with_kubiya_cost
     - time_saved_hours = without_kubiya_hours - with_kubiya_hours
     - time_saved_percentage = (time_saved_hours / without_kubiya_hours) * 100
   - **COMPELLING NARRATIVE**: Create savings_summary that emphasizes the concrete savings:
     - "By using Kubiya, you saved $X and Y hours"
     - Show the contrast: "Without Kubiya: $X (Y hours)" vs "With Kubiya: $X (Y hours)"
9. Be specific and actionable in all fields
10. Output ONLY valid JSON, no markdown formatting
"""

    return planning_prompt
