"""
Output Formatter – writes the ProductionPlan as Markdown and JSON.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path

from models import ProductionPlan

logger = logging.getLogger(__name__)


def _scene_to_markdown(scene) -> str:
    """Render a single ProductionScene as a Markdown section."""
    return f"""\
---

### Frame {scene.scene_number} | {scene.time_start} – {scene.time_end}

| Field | Value |
|-------|-------|
| **Duration** | {scene.duration_seconds}s |
| **Camera Shot** | {scene.camera_shot} |
| **Camera Movement** | {scene.camera_movement} |
| **Composition** | {scene.composition} |
| **Environment** | {scene.environment} |
| **Pose / Action** | {scene.pose_action} |
| **Visual Focus** | {scene.visual_focus} |
| **Mood** | {scene.mood} |
| **Cut at** | {scene.cut_point} |
| **Transition** | {scene.transition} |

#### Image Prompt (copy to image generator)

```
{scene.image_prompt}
```

#### Video Prompt (copy to video generator)

```
{scene.video_prompt}
```

#### TTS Text (copy to ElevenLabs)

```
{scene.tts_text}
```

**Voice direction:** {scene.voice_direction or "N/A"}
"""


def save_markdown(plan: ProductionPlan, output_dir: str | Path) -> Path:
    """Write the production plan as a Markdown file."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    md_path = output_dir / "production_plan.md"

    fpm = round(
        plan.total_scenes / max(plan.total_duration_seconds / 60, 0.1)
    )
    lines = [
        f"# Video Production Plan",
        "",
        f"**Title:** {plan.title}",
        f"**Summary:** {plan.summary}",
        f"**Total Duration:** {plan.total_duration_formatted} "
        f"({plan.total_duration_seconds}s)",
        f"**Total Frames:** {plan.total_scenes}",
        f"**Frames/Minute:** ~{fpm}",
        f"**Target Platform:** {plan.target_platform}",
        f"**Character Template:** {plan.character_template_name}",
        f"**Resolution:** {plan.export_settings.resolution} "
        f"({plan.export_settings.aspect_ratio})",
        f"**FPS:** {plan.export_settings.fps}",
        "",
        "## Frames",
    ]

    for scene in plan.scenes:
        lines.append(_scene_to_markdown(scene))

    lines.append("\n## Assembly Instructions\n")
    for instruction in plan.assembly_instructions:
        lines.append(instruction)

    lines.append("\n---\n*Generated by AI Video Production Pipeline*\n")

    md_path.write_text("\n".join(lines), encoding="utf-8")
    logger.info("Markdown saved: %s", md_path)
    return md_path


def save_json(plan: ProductionPlan, output_dir: str | Path) -> Path:
    """Write the production plan as a JSON file."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    json_path = output_dir / "production_plan.json"

    json_path.write_text(
        json.dumps(plan.model_dump(), indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    logger.info("JSON saved: %s", json_path)
    return json_path
