"""PDB Cleaner tool for the Amina CLI."""

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

METADATA = {
    "name": "pdb-cleaner",  # Use hyphens to match CLI command name convention
    "display_name": "PDB Cleaner",
    "category": "utilities",
    "description": "Clean and prepare PDB files for analysis and simulation",
    "modal_function_name": "pdb_cleaner_worker",
    "modal_app_name": "pdb-cleaner-api",
    "status": "available",
    "outputs": {
        "cleaned_pdb_filepath": "Cleaned and standardized PDB file",
        "cleaning_report_filepath": "CSV report with cleaning details",
        "biological_assembly_filepath": "Biological assembly PDB file (if available)",
    },
}

console = Console()


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("pdb-cleaner")
    def run_pdb_cleaner(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file to clean",
            exists=True,
        ),
        preserve_bfactors: bool = typer.Option(
            True,
            "--preserve-bfactors/--reset-bfactors",
            help="Preserve original B-factors in output",
        ),
        add_missing_residues: bool = typer.Option(
            False,
            "--add-missing-residues/--skip-missing-residues",
            help="Attempt to add missing residues (experimental)",
        ),
        output: Path = typer.Option(
            ...,
            "--output",
            "-o",
            help="Output directory for results",
        ),
        job_name: Optional[str] = typer.Option(
            None,
            "--job-name",
            "-j",
            help="Custom job name for output files (default: uses input filename)",
        ),
        background: bool = typer.Option(
            False,
            "--background",
            "-b",
            help="Submit job and return immediately without waiting for completion",
        ),
    ):
        """
        Clean and prepare PDB files for analysis and simulation.

        Removes waters, heterogens, adds hydrogens, and standardizes residues.

        Examples:
            amina run pdb-cleaner --pdb ./1A2J.pdb -o ./output/
            amina run pdb-cleaner --pdb ./structure.pdb --reset-bfactors -o ./output/
            amina run pdb-cleaner --pdb ./1A2J.pdb -j myjob -o ./output/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

        # Read PDB file content
        pdb_content = pdb.read_text()

        params = {
            "pdb_content": pdb_content,
            "input_filename": pdb.stem,  # e.g., "1A2J" from "1A2J.pdb"
            "preserve_bfactors": preserve_bfactors,
            "add_missing_residues": add_missing_residues,
        }

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("pdb-cleaner", params, output, background=background)
