"""CLI handlers for image-based input (embedded, sidecar, and direct image)."""

import argparse
import sys

from .crop_selector import select_crop_with_ai
from .metadata import build_metadata, embed_metadata
from .cli_helpers import (
    EXIT_SUCCESS,
    EXIT_ERROR,
    EXIT_AI_FAILED,
    _resolve_output_path,
    _resolve_overlay_title,
    _resolve_category,
    _apply_postprocess,
    _generate_fanart_if_requested,
    _emit_result,
)
from .cli_modes import _ask_crop_position_manual


def _run_with_image_source(
    args: argparse.Namespace,
    source_image: str,
    tmpdir: str,
    source: str,
    default_reasoning: str,
) -> int:
    """Process a pre-existing image (embedded, sidecar, or input image) as the source."""
    api_key = args.claude_api_key
    crop_position = ""
    reasoning = default_reasoning

    if args.format == "poster":
        cli_crop = getattr(args, "crop_position", None)
        if cli_crop:
            crop_position = cli_crop
            print(f"   ✅ Crop-Position (vorgegeben): {crop_position}", file=sys.stderr)
        elif args.mode == "manual":
            crop_position = _ask_crop_position_manual(source_image)
        else:
            # auto or suggest: use AI crop position
            if not api_key:
                print(
                    "   Error: Claude API key required for AI crop position. "
                    "Set the CLAUDE_API_KEY env variable "
                    "or run: video-thumbnail-creator config set claude.api_key <key>",
                    file=sys.stderr,
                )
                return EXIT_AI_FAILED
            print("   🤖 K.I. bestimmt Crop-Position…", file=sys.stderr)
            try:
                ai_crop, crop_reasoning = select_crop_with_ai(
                    source_image, api_key=api_key, model=args.claude_model
                )
            except RuntimeError as exc:
                print(f"   Error: {exc}", file=sys.stderr)
                return EXIT_AI_FAILED

            if args.mode == "suggest":
                print(
                    f'   🤖 K.I. Crop-Empfehlung: {ai_crop} – "{crop_reasoning}"',
                    file=sys.stderr,
                )
                crop_position = _ask_crop_position_manual(source_image)
                if not crop_position:
                    crop_position = ai_crop
                if crop_position != ai_crop:
                    reasoning = f"{reasoning} | Crop overridden by user (AI: {ai_crop})"
                else:
                    reasoning = f"{reasoning} | Crop: {crop_reasoning}"
            else:  # auto
                crop_position = ai_crop
                reasoning = f"{reasoning} | Crop: {crop_reasoning}"
                print(
                    f'   ✅ Crop-Position: {crop_position} – "{crop_reasoning}"',
                    file=sys.stderr,
                )

    overlay_title = _resolve_overlay_title(args)
    category, category_logo_path = _resolve_category(args)
    note: str | None = getattr(args, "overlay_note", None)
    detected_badges: list[str] = getattr(args, "detected_badges", [])
    poster_path = _resolve_output_path(args.input_path, args.output_dir, args.output_name_suffix)
    try:
        _apply_postprocess(source_image, poster_path, args.format, crop_position, overlay_title,
                           overlay_category=category, overlay_category_logo_path=category_logo_path,
                           overlay_note=note, template=getattr(args, "template", None),
                           badges=detected_badges)
    except Exception as exc:
        print(f"   Error composing output image: {exc}", file=sys.stderr)
        return EXIT_ERROR

    metadata = build_metadata(
        source=source, frame_index=-1, crop_position=crop_position,
        fmt=args.format, mode=args.mode, input_file=args.input_path,
        overlay_title=overlay_title, overlay_category=category or "",
        overlay_category_logo=category_logo_path or "", overlay_note=note or "",
        ai_reasoning=reasoning,
        poster_template=getattr(args, "style", "") or "",
    )
    embed_metadata(poster_path, metadata)

    fanart_path = _generate_fanart_if_requested(args, source_image, None)
    _emit_result(
        poster_path, -1, args.mode, reasoning, args.input_path, args.json,
        fmt=args.format, crop_position=crop_position, overlay_title=overlay_title,
        source=source, overlay_category=category or "", overlay_note=note or "",
        badges=detected_badges or None, fanart_path=fanart_path,
    )
    return EXIT_SUCCESS


def _run_with_embedded(args: argparse.Namespace, source_image: str, tmpdir: str) -> int:
    """Process a video using the embedded cover art image as the source."""
    return _run_with_image_source(
        args, source_image, tmpdir,
        source="embedded",
        default_reasoning="Embedded cover art was used as source image.",
    )


def _run_with_sidecar(args: argparse.Namespace, source_image: str, tmpdir: str) -> int:
    """Process a video using a sidecar image file as the source."""
    return _run_with_image_source(
        args, source_image, tmpdir,
        source="sidecar",
        default_reasoning="Sidecar image file was used as source.",
    )


def _run_with_image(args: argparse.Namespace, source_image: str, tmpdir: str) -> int:
    """Process an image file as the source for poster/landscape creation."""
    return _run_with_image_source(
        args, source_image, tmpdir,
        source="image",
        default_reasoning="Image file was used as source.",
    )
