#!/usr/bin/env python3
"""
Prompt File Reader Module.

Reads transition prompts from JSON files generated by Claude Code.
"""

import json
from pathlib import Path
from typing import Optional


class PromptFileReader:
    """Reader for transition prompts from JSON file."""

    def __init__(self, prompts_file: str) -> None:
        """
        Initialize prompt file reader.

        Args:
            prompts_file: Path to prompts JSON file.

        Raises:
            FileNotFoundError: If prompts file not found.
            json.JSONDecodeError: If file is not valid JSON.
        """
        self.prompts_file = prompts_file

        with open(prompts_file, "r", encoding="utf-8") as f:
            self.data = json.load(f)

        transitions_count = len(self.data.get("transitions", []))
        has_preview = "preview" in self.data and self.data["preview"]

        print(f"Prompts file loaded: {prompts_file}")
        print(f"  Preview prompt: {'Yes' if has_preview else 'No'}")
        print(f"  Transition prompts: {transitions_count}")

    def generate_prompt(
        self,
        frame_start_path: str,
        frame_end_path: str,
        content_context: Optional[str] = None,
    ) -> str:
        """
        Get transition prompt for specified frames.

        Args:
            frame_start_path: Path to start frame image.
            frame_end_path: Path to end frame image.
            content_context: Ignored (for interface compatibility).

        Returns:
            Transition prompt text.

        Raises:
            ValueError: If no prompt found for the transition.
        """
        # Extract slide numbers from filenames
        start_num = int(Path(frame_start_path).stem.split("-")[-1])
        end_num = int(Path(frame_end_path).stem.split("-")[-1])

        print(f"\nReading transition prompt...")
        print(f"  Start: {Path(frame_start_path).name} (slide {start_num})")
        print(f"  End: {Path(frame_end_path).name} (slide {end_num})")

        # Find matching transition
        for transition in self.data.get("transitions", []):
            if transition["from_slide"] == start_num and transition["to_slide"] == end_num:
                prompt = transition["prompt"]
                print(f"  Found transition prompt!")
                print(f"\n{'=' * 60}")
                print(prompt)
                print(f"{'=' * 60}\n")
                return prompt

        raise ValueError(
            f"No transition prompt found: {start_num} -> {end_num}\n"
            "Please ensure the prompts file contains this transition."
        )

    def generate_preview_prompt(self, first_slide_path: str) -> str:
        """
        Get preview prompt for first slide.

        Args:
            first_slide_path: Path to first slide image.

        Returns:
            Preview prompt text.

        Raises:
            ValueError: If no preview prompt in file.
        """
        print(f"\nReading preview prompt...")
        print(f"  Slide: {Path(first_slide_path).name}")

        preview_data = self.data.get("preview")
        if not preview_data:
            raise ValueError("No preview prompt found in prompts file.")

        prompt = preview_data["prompt"]
        print("  Found preview prompt!")

        return prompt


if __name__ == "__main__":
    import os

    test_file = "outputs/20260112_012753/transition_prompts.json"

    if os.path.exists(test_file):
        reader = PromptFileReader(test_file)
        print(f"\nPrompts file loaded successfully.")
    else:
        print(f"Test file not found: {test_file}")
