#!/usr/bin/env python3
"""
Stage S6: Episode Breakdown

Claude splits the story into episodes with scene outlines, dialogue moments,
and flexible grid/duration per episode.
"""

import subprocess
import sys

from lib import claude_env
from pathlib import Path
from datetime import datetime, timezone

sys.path.insert(0, str(Path(__file__).parent.parent))

from lib import save_metadata, ensure_dir
from lib.path_utils_v3 import get_next_iteration
from lib.feedback_history_v5 import get_feedback_history_for_claude


def execute(story_path: Path, inputs: dict,
            feedback: str = None, refined_from: str = None) -> dict:
    """
    Execute Stage S6: Episode Breakdown.

    Args:
        story_path: Path to story project directory
        inputs: {"S2-bible": "001", "S3-style": "001"}
        feedback: User feedback
        refined_from: Iteration being refined
    """
    stage_dir = story_path / "S6-episodes"
    ensure_dir(stage_dir)
    iteration = get_next_iteration(stage_dir)
    iter_path = stage_dir / iteration
    ensure_dir(iter_path)

    print(f"\nStage S6: Episode Breakdown (iteration {iteration})")

    # Resolve inputs
    bible_iter = inputs.get("S2-bible")
    style_iter = inputs.get("S3-style")
    if not bible_iter:
        return {"status": "error", "error": "S2-bible not in inputs"}
    if not style_iter:
        return {"status": "error", "error": "S3-style not in inputs"}

    bible_path = f"S2-bible/{bible_iter}/story_bible.json"
    style_path = f"S3-style/{style_iter}/style.json"

    if not (story_path / bible_path).exists():
        return {"status": "error", "error": f"Story bible not found: {bible_path}"}
    if not (story_path / style_path).exists():
        return {"status": "error", "error": f"Style not found: {style_path}"}

    # Load session
    session_file = story_path / "session.txt"
    if not session_file.exists():
        return {"status": "error", "error": "session.txt not found"}
    session_id = session_file.read_text().strip()

    # Build prompt
    prompt_path = Path(__file__).parent.parent.parent / "prompts" / "story" / "stage_s6_episodes.txt"
    if not prompt_path.exists():
        return {"status": "error", "error": f"Prompt template not found: {prompt_path}"}

    prompt = prompt_path.read_text()
    prompt = prompt.replace("{bible_path}", bible_path)
    prompt = prompt.replace("{style_path}", style_path)

    # Add feedback
    if refined_from:
        fb_history = get_feedback_history_for_claude(story_path, "S6-episodes", refined_from)
        if fb_history:
            prompt += f"\n\n## Previous Feedback\n\n{fb_history}\n"
    if feedback:
        prompt += f"\n\n## User Feedback\n\n{feedback}\n"
        (iter_path / "feedback.txt").write_text(feedback)

    # Output directory
    relative_iter_path = iter_path.relative_to(story_path)
    prompt = f"## Output Directory\n\nWrite ALL output files to: {relative_iter_path}/\n\n{prompt}"
    (iter_path / "prompt.txt").write_text(prompt)

    # Call Claude
    print(f"Session: {session_id}")
    print("Calling Claude to create episode breakdown...")

    try:
        result = subprocess.run(
            ["claude", "--resume", session_id,
             "--allowedTools", "Read,Write,Glob,Grep",
             "-p", prompt],
            capture_output=True, text=True,
            cwd=str(story_path), timeout=600,
            env=claude_env()
        )
        if result.returncode != 0:
            error_detail = result.stderr or result.stdout
            return {"status": "error",
                    "error": f"Claude returned code {result.returncode}: {error_detail}"}
    except subprocess.TimeoutExpired:
        return {"status": "error", "error": "Claude timed out"}

    # Validate output
    episodes_file = iter_path / "episodes.json"
    if not episodes_file.exists():
        return {"status": "error", "error": "episodes.json not created"}

    # Read episode count
    import json
    episodes_data = json.loads(episodes_file.read_text())
    episode_count = episodes_data.get("total_episodes", len(episodes_data.get("episodes", [])))

    # User message
    user_msg_file = iter_path / "user_message.txt"
    user_message = (user_msg_file.read_text().strip() if user_msg_file.exists()
                    else f"Episode breakdown complete: {episode_count} episodes.")

    # Save metadata
    metadata = {
        "stage": "S6-episodes",
        "iteration": iteration,
        "created_at": datetime.now(timezone.utc).isoformat(),
        "based_on": inputs,
        "refined_from": refined_from,
        "rating": None,
        "result": f"S6-episodes/{iteration}/episodes.json",
        "session_id": session_id,
        "episode_count": episode_count,
    }
    save_metadata(iter_path / "metadata.json", metadata)

    print(f"\nGenerated: S6-episodes/{iteration}/episodes.json")
    print(f"  {episode_count} episodes")

    return {
        "status": "success",
        "iteration": iteration,
        "result": f"S6-episodes/{iteration}/episodes.json",
        "user_message": user_message,
        "episode_count": episode_count,
    }
