"""Open Babel file converter tool for the Amina CLI."""

import typer
from pathlib import Path
from typing import Optional, List
from rich.console import Console

METADATA = {
    "name": "obabel-convert",
    "display_name": "Open Babel Converter",
    "category": "utilities",
    "description": "Convert molecular files between formats using OpenBabel",
    "modal_function_name": "obabel_convert_worker",
    "modal_app_name": "obabel-convert-api",
    "status": "available",
    "outputs": {
        "converted_filepath": "First converted molecular file",
        "converted_1": "Second converted molecular file (batch)",
        "converted_2": "Third converted molecular file (batch)",
        "converted_3": "Fourth converted molecular file (batch)",
        "converted_4": "Fifth converted molecular file (batch)",
    },
}

console = Console()

# Supported output formats
SUPPORTED_FORMATS = [
    "sdf",
    "mol",
    "mol2",
    "pdb",
    "xyz",
    "cif",
    "mmcif",
    "pdbqt",
    "smiles",
    "smi",
    "can",
    "inchi",
    "inchikey",
]


def register(app: typer.Typer):
    """Register this tool's command with the app."""
    from amina_cli.commands.tools import run_tool_with_progress

    @app.command("obabel-convert")
    def run_obabel_convert(
        input_files: List[Path] = typer.Option(
            ...,
            "--input",
            "-i",
            help="Input molecular file(s) to convert (can specify multiple)",
            exists=True,
        ),
        convert_to: str = typer.Option(
            ...,
            "--format",
            "-f",
            help=f"Target format ({', '.join(SUPPORTED_FORMATS)})",
        ),
        output: Path = typer.Option(
            ...,
            "--output",
            "-o",
            help="Output directory for converted files",
        ),
        job_name: Optional[str] = typer.Option(
            None,
            "--job-name",
            "-j",
            help="Custom job name for output files (default: random 4-letter code)",
        ),
    ):
        """
        Convert molecular files between formats using OpenBabel.

        Supports batch conversion of multiple files in a single command.
        Common formats: SDF, MOL, MOL2, PDB, XYZ, CIF, PDBQT.

        Examples:
            amina run obabel-convert -i ./ligand.sdf -f pdb -o ./output/
            amina run obabel-convert -i ./mol1.sdf -i ./mol2.sdf -f mol2 -o ./output/
            amina run obabel-convert -i ./structure.pdb -f xyz -j myjob -o ./output/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

        # Validate format
        format_lower = convert_to.lower()
        if format_lower not in SUPPORTED_FORMATS:
            console.print(
                f"[red]Error:[/red] Unsupported format '{convert_to}'. Supported: {', '.join(SUPPORTED_FORMATS)}"
            )
            raise typer.Exit(1)

        # Read file contents
        file_contents = []
        filenames = []
        for input_file in input_files:
            try:
                content = input_file.read_text()
                file_contents.append(content)
                filenames.append(input_file.name)
            except Exception as e:
                console.print(f"[red]Error:[/red] Failed to read {input_file}: {e}")
                raise typer.Exit(1)

        # Build params
        params = {
            "file_contents": file_contents,
            "filenames": filenames,
            "convert_to": format_lower,
        }

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("obabel-convert", params, output)
