from pathlib import Path
from typing import Annotated

import typer

app = typer.Typer()


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

    out_folder: Annotated[Path, typer.Argument(
        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."""
    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.Argument(
        ..., help="The seed image to base the Mozyq video on.")],

    output_json: Annotated[Path, typer.Argument(
        help="Path to output JSON file.")] = Path("mzq.json"),

    width: Annotated[int, typer.Option(
        help="Output width.")] = 630,

    height: Annotated[int, typer.Option(
        help="Output height.")] = 630,

    num_tiles: Annotated[int, typer.Option(
        help="Number of tiles in the grid.")] = 21,

    max_transitions: Annotated[int, typer.Option(
        help="Maximum number of transitions.")] = 10,

):
    """Create a Mozyq JSON file from a folder of images and a seed image."""
    from mozyq.mzq import gen_mzq_json

    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.Argument(
        help="Path to the Mozyq JSON file generated by the mzq command.")],

    out_folder: Annotated[Path, typer.Argument(
        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()
