#!/usr/bin/env python3
"""
Initialize a microdrama story and create take structure.

Usage:
    init_take_v3.py STORY_NAME [--new-take] [--feedback "text"]
"""
import argparse
import sys
from pathlib import Path

# Add lib to path
sys.path.insert(0, str(Path(__file__).parent))

from lib import (
    get_story_path,
    get_take_path,
    get_stage_dirs,
    ensure_dir,
    update_current_symlink,
    get_session_id,
    log_init
)


def create_claude_md(story_path: Path, story_name: str, take: str, session_id: str, feedback_summary: str = "") -> None:
    """
    Create CLAUDE.md file from template.

    Args:
        story_path: Path to story directory
        story_name: Story name
        take: Take number
        session_id: Claude session ID (same for entire story)
        feedback_summary: Feedback from previous takes
    """
    template_path = Path(__file__).parent.parent / "templates" / "CLAUDE.md.template"

    if not template_path.exists():
        print(f"Warning: Template not found at {template_path}")
        return

    template = template_path.read_text()

    # Fill in template variables
    claude_md = template.format(
        story_name=story_name,
        current_take=take,
        current_stage="(not started)",
        session_id=session_id,
        feedback_summary=feedback_summary or "None yet - this is the first take."
    )

    # Write CLAUDE.md
    claude_path = story_path / "CLAUDE.md"
    claude_path.write_text(claude_md)
    print(f"✓ Created {claude_path}")


def init_take(story_name: str, new_take: bool = False, feedback: str = None, story_text: str = None) -> None:
    """
    Initialize a story and create take structure.

    Args:
        story_name: Story name
        new_take: If True, create new take (002, 003, etc.)
        feedback: Feedback text for new take
        story_text: Story content (optional)
    """
    story_path = get_story_path(story_name)

    # Check if story exists
    story_exists = story_path.exists()

    if new_take and not story_exists:
        print(f"Error: Cannot create new take for non-existent story '{story_name}'")
        print(f"Run without --new-take to create the story first.")
        sys.exit(1)

    # Determine take number
    if story_exists and new_take:
        # Find ALL existing takes by scanning directory
        # NEVER overwrite - always create next number
        existing_takes = []
        for item in story_path.iterdir():
            if item.is_dir() and item.name.isdigit() and len(item.name) == 3:
                try:
                    existing_takes.append(int(item.name))
                except ValueError:
                    continue

        if existing_takes:
            # Get highest take number and increment
            max_take = max(existing_takes)
            take_num = max_take + 1
            previous_take = f"{max_take:03d}"
            print(f"Found existing takes: {sorted(existing_takes)}")
            print(f"Creating take {take_num:03d} (previous: {previous_take})")
        else:
            # No takes found (shouldn't happen for --new-take but handle it)
            print(f"Warning: No existing takes found, creating 001")
            take_num = 1
            previous_take = None
    else:
        # First take
        take_num = 1
        previous_take = None

    take = f"{take_num:03d}"

    # Safety check: NEVER overwrite existing take
    take_path_check = story_path / take
    assert not take_path_check.exists(), f"Take {take} already exists at {take_path_check} - NEVER overwrite takes!"

    # Create story directory
    ensure_dir(story_path)

    # Create pipeline.log if it doesn't exist
    pipeline_log = story_path / "pipeline.log"
    if not pipeline_log.exists():
        pipeline_log.touch()
        print(f"✓ Created {pipeline_log}")

    # Create or update story.md
    story_md = story_path / "story.md"
    if not story_md.exists() or story_text:
        if story_text:
            # Use provided story text
            story_md.write_text(f"# {story_name.replace('-', ' ').title()}\n\n{story_text}\n")
            print(f"✓ Created {story_md} with provided story text")
        else:
            # Create placeholder
            story_md.write_text(f"# {story_name.replace('-', ' ').title()}\n\n[Paste your story here]\n")
            print(f"✓ Created {story_md}")
            print(f"  → Edit this file and add your story text")

    # Generate or load session ID (one per story, reused across takes)
    session_file = story_path / "session.txt"
    if session_file.exists():
        # Reuse existing session ID
        session_id = session_file.read_text().strip()
        print(f"✓ Reusing session ID: {session_id}")
    else:
        # Generate new session ID for this story
        session_id = get_session_id(story_name)
        session_file.write_text(session_id)
        print(f"✓ Created session ID: {session_id}")

    # Create take directory
    take_path = story_path / take
    ensure_dir(take_path)
    print(f"✓ Created take {take} at {take_path}")

    # Create all stage directories
    stage_dirs = get_stage_dirs()

    for stage_name, stage_dir in stage_dirs.items():
        stage_path = take_path / stage_dir
        ensure_dir(stage_path)

        # Create 001 iteration
        iter_001 = stage_path / "001"
        ensure_dir(iter_001)

        # For 01-story, copy story.md
        if stage_dir == "01-story":
            (iter_001 / "story.md").write_text(story_md.read_text())

            # Create basic metadata
            metadata = {
                "stage": "01-story",
                "take": take,
                "iteration": "001",
                "source": "../../../story.md"
            }

            import json
            (iter_001 / "metadata.json").write_text(json.dumps(metadata, indent=2))

        # Create current symlink
        update_current_symlink(stage_path, "001")

    print(f"✓ Created {len(stage_dirs)} stage directories with 001 iterations")

    # Update story-level current symlink
    update_current_symlink(story_path, take)
    print(f"✓ Set current take to {take}")

    # Collect feedback summary if new take
    feedback_summary = ""
    if previous_take and feedback:
        feedback_summary = f"""## Take {previous_take} Feedback

{feedback}

Use this feedback to guide your work on take {take}.
"""

    # Create CLAUDE.md
    create_claude_md(story_path, story_name, take, session_id, feedback_summary)

    # Log initialization
    log_init(story_name, take, previous_take)

    # Print success message
    print(f"\n{'='*60}")
    print(f"Story '{story_name}' initialized!")
    print(f"{'='*60}")
    print(f"Story path: {story_path}")
    print(f"Current take: {take}")

    if not story_exists:
        print(f"\nNext steps:")
        print(f"1. Edit {story_md} and add your story")
        print(f"2. Run: python run_stage_v3.py '{story_name}' --stage understanding")
    else:
        print(f"\nPrevious take: {previous_take}")
        if feedback:
            print(f"Feedback: {feedback}")
        print(f"\nNext step:")
        print(f"Run: python run_stage_v3.py '{story_name}' --stage understanding")


def main():
    parser = argparse.ArgumentParser(
        description="Initialize microdrama story and create take structure"
    )
    parser.add_argument("story_name", help="Story name (e.g., 'fire-truck-brakes')")
    parser.add_argument(
        "--new-take",
        action="store_true",
        help="Create new take (002, 003, etc.)"
    )
    parser.add_argument(
        "--feedback",
        help="Feedback from previous take (used with --new-take)"
    )
    parser.add_argument(
        "--story",
        help="Story text (quote if multi-line)"
    )
    parser.add_argument(
        "--story-file",
        help="Path to file containing story text"
    )

    args = parser.parse_args()

    # Validate arguments
    if args.feedback and not args.new_take:
        print("Error: --feedback requires --new-take")
        sys.exit(1)

    if args.story and args.story_file:
        print("Error: Cannot specify both --story and --story-file")
        sys.exit(1)

    # Get story text
    story_text = None
    if args.story:
        story_text = args.story
    elif args.story_file:
        story_file = Path(args.story_file)
        if not story_file.exists():
            print(f"Error: Story file not found: {args.story_file}")
            sys.exit(1)
        story_text = story_file.read_text()

    init_take(args.story_name, args.new_take, args.feedback, story_text)


if __name__ == "__main__":
    main()
