"""
Markdown Writer Node - Converts curriculum to a formatted markdown file.
"""

from typing import Dict, Any
from datetime import datetime
from state import State
from tools import write_markdown_file


class MarkdownWriterNode:
    """
    Convert the curriculum to a well-formatted markdown document.
    Saves the file to the sandbox directory.
    """
    def __init__(self):
        """Initialize the markdown writer node."""
        pass

    def execute(self, state: State) -> Dict[str, Any]:
        """Execute the markdown writer node."""
        topic = state["topic"]
        curriculum = state.get("curriculum")
        if not curriculum:
            return {
                "markdown_content": None,
                "markdown_path": None,
                "messages": [{"role": "assistant", "content": "Error: No curriculum to write."}]
            }
        
        markdown = self._generate_markdown(topic, curriculum, state)
        safe_topic = topic.lower().replace(" ", "_").replace("/", "_")
        filename = f"learning_path_{safe_topic}"
        write_markdown_file(filename, markdown)
        from tools import SANDBOX_DIR
        filepath = str(SANDBOX_DIR / f"{filename}.md")
        return {
            "markdown_content": markdown,
            "markdown_path": filepath,
            "messages": [{"role": "assistant", "content": f"Markdown file created: {filepath}"}]
        }
    
    def _generate_markdown(self, topic: str, curriculum, state: State) -> str:
        """Generate formatted markdown content from curriculum."""
        md = f"""# Learning Path: {topic}

> Generated on {datetime.now().strftime("%Y-%m-%d")}

## Overview

{curriculum.overview}

**Estimated Duration:** {curriculum.total_estimated_days} days  
**Skill Level:** {state.get("current_skill_level", "beginner")}  
**Time Commitment:** {state.get("time_commitment", "1hr/day")}

---

## Prerequisites

"""
        prerequisites = state.get("prerequisites", [])
        if prerequisites:
            for prereq in prerequisites:
                md += f"- {prereq}\n"
        else:
            md += "- No specific prerequisites identified\n"
        
        md += "\n---\n\n## Learning Phases\n\n"
        
        for milestone in curriculum.milestones:
            md += f"""### Phase {milestone.phase_number}: {milestone.title}

**Goal:** {milestone.goal}

{milestone.description}

#### Resources

| Resource | Type | Difficulty |
|----------|------|------------|
"""
            for resource in milestone.resources:
                md += f"| [{resource.title}]({resource.url}) | {resource.type} | {resource.difficulty} |\n"
            
            if milestone.project_idea:
                md += f"""
#### Hands-on Project

{milestone.project_idea}

"""
            
            md += f"**Estimated Duration:** {milestone.estimated_days} days\n\n---\n\n"
        
        md += f"""## Summary

This learning path covers {len(curriculum.milestones)} phases to help you master {topic}.

**Total Time:** {curriculum.total_estimated_days} days at {state.get("time_commitment", "1hr/day")}

---

*Generated by Learning Path Generator*
"""
        
        return md
