import json
import os

from .screenshots import extract_frame


class MarkdownGenerator:
    def __init__(self, session_dir: str):
        self.session_dir = session_dir
        self.analysis_path = os.path.join(session_dir, "analysis.json")
        self.video_path = os.path.join(session_dir, "recording.mp4")

    def generate(self):
        if not os.path.exists(self.analysis_path):
            return None

        with open(self.analysis_path) as f:
            analysis = json.load(f)

        md_content = "# Project Tutorial\n\n"

        screenshots_dir = os.path.join(self.session_dir, "screenshots")
        os.makedirs(screenshots_dir, exist_ok=True)

        for step in analysis.get("steps", []):
            md_content += f"## {step['title']}\n\n"
            md_content += f"{step['description']}\n\n"

            # Extract screenshot for the step
            screenshot_name = f"step_{step['id']}.png"
            screenshot_path = os.path.join(screenshots_dir, screenshot_name)
            if extract_frame(self.video_path, step["start_ms"], screenshot_path):
                md_content += f"![{step['title']}](./screenshots/{screenshot_name})\n\n"

            # Add commands if present
            commands = [e for e in step.get("events", []) if e.get("type") == "command"]
            if commands:
                md_content += "```bash\n"
                for cmd in commands:
                    md_content += f"{cmd['command']}\n"
                md_content += "```\n\n"

        output_path = os.path.join(self.session_dir, "tutorial.md")
        with open(output_path, "w") as f:
            f.write(md_content)

        return output_path
