"""nb-to-script command for nblite CLI."""

from __future__ import annotations

from pathlib import Path
from typing import Annotated

import typer

from nblite.cli._helpers import console
from nblite.cli.app import app
from nblite.config.schema import CellReferenceStyle, ExportMode
from nblite.core.notebook import Format, Notebook


@app.command(name="nb-to-script")
def nb_to_script(
    ctx: typer.Context,
    input_path: Annotated[
        Path,
        typer.Argument(help="Input notebook path"),
    ],
    output_path: Annotated[
        Path,
        typer.Argument(
            help="Output script path. If not provided, the output path will be printed to standard output."
        ),
    ] = None,
    input_format: Annotated[
        Format,
        typer.Option(
            "--input-format",
            help=f"Input format. Available formats: {', '.join([f.value for f in Format])}",
        ),
    ] = Format.IPYNB,
    export_mode: Annotated[
        ExportMode,
        typer.Option(
            "--export-mode",
            help=f"Export mode. Available modes: {', '.join([m.value for m in ExportMode])}",
        ),
    ] = ExportMode.PERCENT,
    cell_reference_style: Annotated[
        CellReferenceStyle,
        typer.Option(
            "--cell-reference-style",
            help=f"Cell reference style. Available styles: {', '.join([s.value for s in CellReferenceStyle])}",
        ),
    ] = CellReferenceStyle.RELATIVE,
    include_warning: Annotated[
        bool,
        typer.Option("--include-warning", help="Include autogenerated warning header"),
    ] = True,
    target_module: Annotated[
        str | None,
        typer.Option(
            "--target-module",
            help="Target module. If not provided, the notebook will be exported to the root module.",
        ),
    ] = None,
) -> None:
    """Convert a notebook to a python script.

    This works similarly to 'nbl export', in that notebooks get converted to Python modules.
    But this command can be used for single notebooks, whereas 'nbl export' is for entire code locations.
    This is to facilitate the usage of notebooks as scripts.

    Any cell with a #|export directive will be exported to the python output file.

    Example:
        nbl nb-to-script input.ipynb output.py
        nbl nb-to-script input.ipynb  # Print content to stdout
    """
    import tempfile

    from nblite.core.directive import Directive
    from nblite.export.pipeline import export_notebook_to_module

    nb = Notebook.from_file(input_path, format=input_format)
    nb.directives["default_exp"] = [Directive(name="default_exp", value="main")]

    # If no output path provided, export to temp file and print to stdout
    if output_path is None:
        with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as tmp:
            tmp_path = Path(tmp.name)

        export_notebook_to_module(
            nb,
            tmp_path,
            project_root=Path.cwd(),
            export_mode=export_mode,
            include_warning=include_warning,
            cell_reference_style=cell_reference_style,
            package_name=None,
            target_module="main",
        )

        # Print content to stdout
        print(tmp_path.read_text())
        tmp_path.unlink()
    else:
        export_notebook_to_module(
            nb,
            output_path,
            project_root=Path.cwd(),
            export_mode=export_mode,
            include_warning=include_warning,
            cell_reference_style=cell_reference_style,
            package_name=None,
            target_module="main",
        )
        console.print(f"[green]Exported {input_path} to {output_path}[/green]")
