from pathlib import Path
from typing import Annotated

import typer

app = typer.Typer()


@app.command('normalize')
def mzq_normalize(
    in_folder: Annotated[Path, typer.Option(
        help='Input folder with images to normalize.')],

    out_folder: Annotated[Path, typer.Option(
        help='Output folder for normalized images.')],

    min_width: Annotated[int, typer.Option(
        help='Minimum width of input images.')] = 630,

    min_height: Annotated[int, typer.Option(
        help='Minimum height of input images.')] = 630,

    target_width: Annotated[int, typer.Option(
        help='Target width of output images.')] = 630,

    target_height: Annotated[int, typer.Option(
        help='Target height of output images.')] = 630,
):
    '''
    Normalize images in a folder to a specific size and format.
    Images smaller than the minimum dimensions will be skipped.
    Output images will be resized and center-cropped to the target dimensions.
    '''
    from mozyq.norm import normalize

    normalize(
        in_folder=in_folder,
        out_folder=out_folder,
        min_width=min_width,
        min_height=min_height,
        target_width=target_width,
        target_height=target_height)


@app.command('json')
def mzq_json(
        master: Annotated[Path, typer.Option(
            help='The seed image to base the Mozyq video on.')],

        width: Annotated[
            int,
            typer.Option(
                help='The output width (overrides resolution for rectangular videos)')] = 630,

        height: Annotated[
            int,
            typer.Option(
                help='The output height (overrides resolution for rectangular videos)')] = 630,

        num_tiles: Annotated[
            int,
            typer.Option(
                help='The number of tiles in the grid. Must be odd and must divide evenly into the video dimensions.')] = 21,

        max_transitions: int = 10,
        output_json: Path = Path('mzq.json')
):
    '''
    Create a Mozyq JSON file from a a folder of images and a seed image.
    '''
    from mozyq.mzq import gen_mzq_json

    # Determine final dimensions
    gen_mzq_json(
        master=master,
        tile_folder=master.parent,
        width=width,
        height=height,
        num_tiles=num_tiles,
        max_transitions=max_transitions,
        output_json=output_json)


@app.command('frames')
def mzq_frames(
    mzq_json: Annotated[Path, typer.Option(
        help='Path to the Mozyq JSON file generated by the mzq command.')],
    out_folder: Annotated[Path, typer.Option(
        help='Output folder for the frames.')]
):
    '''
    Generate frames from a Mozyq JSON file.
    '''
    import json

    from cattrs import structure
    from mozyq_types import Mozyq

    from mozyq.frame import frames

    with open(mzq_json) as f:
        mzqs = [
            structure(mzq, Mozyq)
            for mzq in json.load(f)]

    frames(mzqs, out_folder)


def main():
    app()
