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

Handles path validation, symlink management, and directory structure.
"""
from pathlib import Path
from typing import Optional


BASE_DIR = Path("/mnt/video/microdrama-v3")


def get_story_path(story_name: str) -> Path:
    """Get base path for a story."""
    return BASE_DIR / story_name


def get_take_path(story_name: str, take: str = "current") -> Path:
    """
    Get path to a take directory.

    Args:
        story_name: Story name
        take: Take number (e.g., "001") or "current"

    Returns:
        Path to take directory

    Raises:
        ValueError: If take doesn't exist or current symlink is broken
    """
    story_path = get_story_path(story_name)

    if not story_path.exists():
        raise ValueError(f"Story '{story_name}' not found at {story_path}")

    if take == "current":
        current_link = story_path / "current"
        if not current_link.exists():
            raise ValueError(f"No current take set for '{story_name}'")
        if not current_link.is_symlink():
            raise ValueError(f"'current' is not a symlink in {story_path}")
        take = current_link.readlink().name

    take_path = story_path / take
    if not take_path.exists():
        raise ValueError(f"Take {take} not found for '{story_name}'")

    return take_path


def get_stage_path(
    story_name: str,
    stage: str,
    take: str = "current",
    iteration: str = "current"
) -> Path:
    """
    Get path to a stage iteration directory.

    Args:
        story_name: Story name
        stage: Stage directory name (e.g., "02-understanding")
        take: Take number or "current"
        iteration: Iteration number (e.g., "001") or "current"

    Returns:
        Path to stage iteration directory

    Raises:
        ValueError: If any path component doesn't exist
    """
    take_path = get_take_path(story_name, take)
    stage_path = take_path / stage

    if not stage_path.exists():
        raise ValueError(f"Stage '{stage}' not found in take {take_path.name}")

    if iteration == "current":
        current_link = stage_path / "current"
        if not current_link.exists():
            raise ValueError(f"No current iteration set for stage '{stage}'")
        if not current_link.is_symlink():
            raise ValueError(f"'current' is not a symlink in {stage_path}")
        iteration = current_link.readlink().name

    iter_path = stage_path / iteration
    if not iter_path.exists():
        raise ValueError(f"Iteration {iteration} not found for stage '{stage}'")

    return iter_path


def get_next_iteration(stage_path: Path) -> str:
    """
    Get next iteration number for a stage.

    Args:
        stage_path: Path to stage directory

    Returns:
        Next iteration number as string (e.g., "002")
    """
    if not stage_path.exists():
        return "001"

    iterations = [
        d.name for d in stage_path.iterdir()
        if d.is_dir() and d.name.isdigit()
    ]

    if not iterations:
        return "001"

    max_iter = max(int(i) for i in iterations)
    return f"{max_iter + 1:03d}"


def update_current_symlink(parent_path: Path, target: str) -> None:
    """
    Update 'current' symlink to point to target.

    Args:
        parent_path: Parent directory containing the symlink
        target: Target directory name (relative to parent)
    """
    current_link = parent_path / "current"

    # Remove existing symlink
    if current_link.exists() or current_link.is_symlink():
        current_link.unlink()

    # Create new symlink
    current_link.symlink_to(target)


def ensure_dir(path: Path) -> None:
    """Create directory if it doesn't exist."""
    path.mkdir(parents=True, exist_ok=True)


def get_stage_dirs() -> dict:
    """
    Get mapping of stage names to directory names.

    Returns:
        Dict mapping stage name to directory name
    """
    return {
        "story": "01-story",
        "understanding": "02-understanding",
        "script": "03-script",
        "assets": "04-assets",
        "references": "05-references",
        "characteristic": "06-characteristic",
        "grid": "07-grids",
        "script-adapted": "08-script-adapted",
        "frames": "09-frames",
        "videos": "10-videos",
        "assembly": "11-assembly"
    }


def validate_story_structure(story_name: str) -> bool:
    """
    Validate that story has proper directory structure.

    Args:
        story_name: Story name

    Returns:
        True if structure is valid
    """
    story_path = get_story_path(story_name)

    if not story_path.exists():
        return False

    # Check for pipeline.log
    if not (story_path / "pipeline.log").exists():
        return False

    # Check for at least one take
    takes = [d for d in story_path.iterdir() if d.is_dir() and d.name.isdigit()]
    if not takes:
        return False

    # Check for current symlink
    current_link = story_path / "current"
    if not current_link.is_symlink():
        return False

    return True
