"""
Present the levers in a human readable format.
Where the vital few are presented first, and the non-vital at the end.

Input files:
- enrich_potential_levers_19dc0718-3df7-48e3-b06d-e2c664ecc07d.json
- focus_on_vital_few_levers_19dc0718-3df7-48e3-b06d-e2c664ecc07d.json

Output file:
- strategic_decisions_markdown_19dc0718-3df7-48e3-b06d-e2c664ecc07d.md

PROMPT> python -m worker_plan_internal.lever.strategic_decisions_markdown
"""
import logging
from pydantic import BaseModel
from typing import List, Dict, Any

logger = logging.getLogger(__name__)

class EnrichLever(BaseModel):
    """Represents a single lever generated by the enrich_potential_levers.py module."""
    lever_id: str
    name: str
    consequences: str
    options: List[str]
    review: str
    description: str
    synergy_text: str
    conflict_text: str

class VitalLever(BaseModel):
    """Represents a single lever generated by the focus_on_vital_few_levers.py module."""
    lever_id: str
    name: str
    consequences: str
    options: List[str]
    review: str
    description: str
    synergy_text: str
    conflict_text: str

class LeverAssessment(BaseModel):
    """Represents the assessment of a single lever from the focus_on_vital_few_levers.py module."""
    lever_id: str
    lever_name: str
    strategic_importance: str
    justification: str

class StrategicDecisionsMarkdown:
    def __init__(self, enrich_levers: List[Dict[str, Any]], vital_levers: List[Dict[str, Any]], vital_levers_summary: str, lever_assessments: List[Dict[str, Any]]):
        # Convert dictionaries to Pydantic models
        self.enrich_levers = [EnrichLever(**lever) for lever in enrich_levers]
        self.vital_levers = [VitalLever(**lever) for lever in vital_levers]
        self.vital_levers_summary = vital_levers_summary.strip()
        
        # Convert assessment data to Pydantic models
        self.lever_assessments = {}
        if lever_assessments:
            for assessment in lever_assessments:
                assessment_model = LeverAssessment(**assessment)
                self.lever_assessments[assessment_model.lever_id] = assessment_model
    
    def to_markdown(self) -> str:
        """Generate markdown content with vital levers first, then the rest."""
        rows = []
        
        # Add vital levers section
        rows.append("## Primary Decisions")
        rows.append("The vital few decisions that have the most impact.\n")

        if len(self.vital_levers_summary) > 0:
            rows.append(f"\n{self.vital_levers_summary}\n")
        
        for i, lever in enumerate(self.vital_levers):
            lever_index = i + 1
            rows.append(f"### Decision {lever_index}: {lever.name}")
            rows.append(f"**Lever ID:** `{lever.lever_id}`\n")
            rows.append(f"**The Core Decision:** {lever.description}\n")
            rows.append(f"**Why It Matters:** {lever.consequences}\n")
            rows.append("**Strategic Choices:**\n")
            for option_index, option in enumerate(lever.options, 1):
                rows.append(f"{option_index}. {option}")
            rows.append(f"\n**Trade-Off / Risk:** {lever.review}\n")
            rows.append("**Strategic Connections:**\n")
            rows.append(f"**Synergy:** {lever.synergy_text}\n")
            rows.append(f"**Conflict:** {lever.conflict_text}\n")

            # Add assessment information if available
            if lever.lever_id in self.lever_assessments:
                assessment = self.lever_assessments[lever.lever_id]
                rows.append(f"**Justification:** *{assessment.strategic_importance}*, {assessment.justification}\n")
            
        # Filter out levers that are already in vital section
        vital_lever_ids = {lever.lever_id for lever in self.vital_levers}
        additional_levers = [lever for lever in self.enrich_levers if lever.lever_id not in vital_lever_ids]
        
        # logger.info(f"Filtered out {len(self.enrich_levers) - len(additional_levers)} duplicate levers from additional section.")
        
        # Add remaining levers section
        rows.append("---")
        rows.append("## Secondary Decisions")
        rows.append("These decisions are less significant, but still worth considering.\n")
        
        for i, lever in enumerate(additional_levers):
            lever_index = len(self.vital_levers) + i + 1
            rows.append(f"### Decision {lever_index}: {lever.name}")
            rows.append(f"**Lever ID:** `{lever.lever_id}`\n")
            rows.append(f"**The Core Decision:** {lever.description}\n")
            rows.append(f"**Why It Matters:** {lever.consequences}\n")
            rows.append("**Strategic Choices:**\n")
            for option_index, option in enumerate(lever.options, 1):
                rows.append(f"{option_index}. {option}")
            rows.append(f"\n**Trade-Off / Risk:** {lever.review}\n")
            rows.append("**Strategic Connections:**\n")
            rows.append(f"**Synergy:** {lever.synergy_text}\n")
            rows.append(f"**Conflict:** {lever.conflict_text}\n")

            # Add assessment information if available
            if lever.lever_id in self.lever_assessments:
                assessment = self.lever_assessments[lever.lever_id]
                rows.append(f"**Justification:** *{assessment.strategic_importance}*, {assessment.justification}\n")
        
        return "\n".join(rows)
    
    def save_markdown(self, filename: str):
        """Save the markdown content to a file."""
        markdown_content = self.to_markdown()
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(markdown_content)

if __name__ == "__main__":
    from worker_plan_internal.prompt.prompt_catalog import PromptCatalog
    import os
    import json

    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    prompt_catalog = PromptCatalog()
    prompt_catalog.load_simple_plan_prompts()

    prompt_id = "19dc0718-3df7-48e3-b06d-e2c664ecc07d"
    prompt_item = prompt_catalog.find(prompt_id)
    if not prompt_item:
        raise ValueError("Prompt item not found.")
    project_plan = prompt_item.prompt

    enrich_potential_levers_filename = f"enrich_potential_levers_{prompt_id}.json"
    vital_levers_filename = f"focus_on_vital_few_levers_{prompt_id}.json"

    # Load the enriched levers
    enrich_potential_levers_file = os.path.join(os.path.dirname(__file__), 'test_data', enrich_potential_levers_filename)
    if not os.path.exists(enrich_potential_levers_file):
        logger.error(f"Enriched levers file not found at: {enrich_potential_levers_file!r}. Please run enrich_potential_levers.py first.")
        exit(1)
    with open(enrich_potential_levers_file, 'r', encoding='utf-8') as f:
        characterized_data = json.load(f)
    raw_levers_list = characterized_data.get('characterized_levers', [])
    logger.info(f"Loaded {len(raw_levers_list)} enriched levers.")

    # Load the vital levers and assessments
    vital_levers_file = os.path.join(os.path.dirname(__file__), 'test_data', vital_levers_filename)
    if not os.path.exists(vital_levers_file):
        logger.error(f"Vital levers file not found at: {vital_levers_file!r}. Please run focus_on_vital_few_levers.py first.")
        exit(1)
    with open(vital_levers_file, 'r', encoding='utf-8') as f:
        vital_data = json.load(f)
    vital_levers_list = vital_data.get('levers', [])
    lever_assessments_list = vital_data.get('response', {}).get('lever_assessments', [])
    vital_levers_summary = vital_data.get('response', {}).get('summary', '')
    logger.info(f"Loaded {len(vital_levers_list)} vital levers and {len(lever_assessments_list)} assessments.")

    markdown_with_levers = StrategicDecisionsMarkdown(raw_levers_list, vital_levers_list, vital_levers_summary, lever_assessments_list)
    markdown_content = markdown_with_levers.to_markdown()

    # Save the markdown file
    output_filename = f"strategic_decisions_markdown_{prompt_id}.md"
    markdown_with_levers.save_markdown(output_filename)
    logger.info(f"Saved markdown file to {output_filename!r}")