"""Agent 6: Multi-Problem Combiner.

Combines multiple problems into a single comprehensive problem.
Supports cross-subject combinations (physics + chemistry).
"""

from typing import Optional, List, Dict

from vbagent.agents.base import create_agent, run_agent_sync
from vbagent.config import get_config
from vbagent.models.classification import CombinedProblem


def get_problem_combiner_prompt() -> str:
    """Get problem combiner prompt."""
    return """You are an expert problem combiner. Combine multiple problems into a single comprehensive problem that integrates concepts naturally.

You MUST respond with ONLY a valid JSON object:

{
    "combined_problem_latex": "<complete combined LaTeX problem>",
    "combined_solution_latex": "<complete solution addressing all parts>",
    "combined_ideas": ["<idea1>", "<idea2>"],
    "source_problems": [<problem_id1>, <problem_id2>],
    "combination_metadata": {
        "strategy_used": "sequential" | "parallel" | "nested",
        "subjects_combined": ["<subject1>", "<subject2>"],
        "connection_points": ["<connection1>", "<connection2>"],
        "difficulty_justification": "<why this difficulty>"
    }
}

Combination strategies:
1. **sequential**: Problems solved one after another, output of one feeds into next
2. **parallel**: Independent problems in same context/scenario
3. **nested**: One problem embedded within another

Cross-subject combinations:
- Physics + Chemistry: Thermodynamics + chemical reactions, electrochemistry + circuits
- Physics + Math: Calculus-based mechanics, differential equations
- Chemistry + Math: Kinetics with calculus, equilibrium calculations

Quality guidelines:
1. Create natural, realistic scenarios
2. Ensure smooth transitions between concepts
3. Maintain logical flow
4. Avoid forced combinations
5. Keep combined problem solvable
6. Adjust difficulty appropriately

LaTeX formatting:
- Use \\item for main problem
- Use (a), (b), (c) for sub-parts if needed
- Maintain consistent notation
- Include all necessary diagrams

Respond with ONLY the JSON object."""


def create_problem_combiner_agent():
    """Create problem combiner agent."""
    prompt = get_problem_combiner_prompt()
    
    return create_agent(
        name="ProblemCombiner",
        instructions=prompt,
        output_type=CombinedProblem,
        agent_type="variant",
    )


def combine_problems(
    problems: List[Dict[str, str]],
    strategy: str = "sequential",
    target_difficulty: str = "hard",
    cross_subject: bool = False
) -> CombinedProblem:
    """Combine multiple problems (Agent 6).
    
    Args:
        problems: List of problem dicts with keys: id, latex, solution, subject, topic
        strategy: Combination strategy (sequential, parallel, nested)
        target_difficulty: Target difficulty for combined problem
        cross_subject: Whether to combine across subjects
        
    Returns:
        CombinedProblem with integrated content
    """
    agent = create_problem_combiner_agent()
    
    # Build context
    problems_str = ""
    for i, prob in enumerate(problems, 1):
        problems_str += f"""
**Problem {i}** (ID: {prob.get('id', i)})
Subject: {prob.get('subject', 'physics')}
Topic: {prob.get('topic', 'unknown')}

LaTeX:
```latex
{prob['latex']}
```

Solution:
```latex
{prob.get('solution', 'Not provided')}
```
"""
    
    subjects = list(set(p.get('subject', 'physics') for p in problems))
    
    context = f"""Combine these problems into a single comprehensive problem.

**Combination Strategy:** {strategy}
**Target Difficulty:** {target_difficulty}
**Cross-Subject:** {cross_subject}
**Subjects Involved:** {', '.join(subjects)}

{problems_str}

Create a natural, well-integrated combined problem."""
    
    result = run_agent_sync(agent, context)
    return result
