#!/usr/bin/env python3
"""
Metadata utilities for microdrama v3 workflow.

Handles metadata.json creation and reading.
"""
import json
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any


def create_metadata(
    stage: str,
    take: str,
    iteration: str,
    source: Optional[str] = None,
    model: Optional[str] = None,
    prompt_template: Optional[str] = None,
    session_id: Optional[str] = None,
    **kwargs
) -> Dict[str, Any]:
    """
    Create metadata dictionary.

    Args:
        stage: Stage name
        take: Take number
        iteration: Iteration number
        source: Source file path (relative)
        model: Model used (e.g., "claude-sonnet-4.5", "nanobanana")
        prompt_template: Prompt template file path
        session_id: Claude session ID
        **kwargs: Additional metadata fields

    Returns:
        Metadata dictionary
    """
    metadata = {
        "stage": stage,
        "take": take,
        "iteration": iteration,
        "timestamp": datetime.now().isoformat()
    }

    if source:
        metadata["source"] = source
    if model:
        metadata["model"] = model
    if prompt_template:
        metadata["prompt_template"] = prompt_template
    if session_id:
        metadata["session_id"] = session_id

    # Add any additional fields
    metadata.update(kwargs)

    return metadata


def save_metadata(path: Path, metadata: Dict[str, Any]) -> None:
    """
    Save metadata to JSON file.

    Args:
        path: Path to metadata.json
        metadata: Metadata dictionary
    """
    with open(path, "w") as f:
        f.write(json.dumps(metadata, indent=2))


def load_metadata(path: Path) -> Dict[str, Any]:
    """
    Load metadata from JSON file.

    Args:
        path: Path to metadata.json

    Returns:
        Metadata dictionary
    """
    with open(path) as f:
        return json.load(f)


def add_feedback(
    metadata_path: Path,
    feedback: str,
    led_to_iteration: Optional[str] = None
) -> None:
    """
    Add feedback to metadata.

    Args:
        metadata_path: Path to metadata.json
        feedback: User feedback text
        led_to_iteration: Iteration number this feedback led to
    """
    metadata = load_metadata(metadata_path)

    metadata["feedback"] = {
        "from_user": feedback,
        "timestamp": datetime.now().isoformat()
    }

    if led_to_iteration:
        metadata["feedback"]["led_to_iteration"] = led_to_iteration

    save_metadata(metadata_path, metadata)


def add_previous_iteration(
    metadata_path: Path,
    previous_path: str,
    reason: str
) -> None:
    """
    Add previous iteration reference to metadata.

    Args:
        metadata_path: Path to metadata.json
        previous_path: Path to previous iteration
        reason: Reason for creating new iteration
    """
    metadata = load_metadata(metadata_path)

    metadata["previous_iteration"] = {
        "path": previous_path,
        "rejected_because": reason
    }

    save_metadata(metadata_path, metadata)


def get_session_id(story_name: str) -> str:
    """
    Generate Claude session ID for a story.

    Single session ID used for ENTIRE story (all takes, all stages).
    Claude maintains full context and can reference previous work,
    even across takes. Claude Code handles summarization automatically
    for long conversations.

    Args:
        story_name: Story name

    Returns:
        Session ID string (UUID format required by Claude CLI)
    """
    import uuid

    # Generate UUID for Claude CLI session
    return str(uuid.uuid4())


def save_prompt(path: Path, prompt: str) -> None:
    """
    Save prompt to text file.

    Args:
        path: Path to prompt.txt
        prompt: Prompt text
    """
    with open(path, "w") as f:
        f.write(prompt)


def load_prompt(path: Path) -> str:
    """
    Load prompt from text file.

    Args:
        path: Path to prompt.txt

    Returns:
        Prompt text
    """
    with open(path) as f:
        return f.read()


def save_session_id(path: Path, session_id: str) -> None:
    """
    Save session ID to text file.

    Args:
        path: Path to session.txt
        session_id: Session ID
    """
    with open(path, "w") as f:
        f.write(session_id)


def load_session_id(path: Path) -> str:
    """
    Load session ID from text file.

    Args:
        path: Path to session.txt

    Returns:
        Session ID
    """
    with open(path) as f:
        return f.read().strip()
