"""P2Rank binding site prediction tool for the Amina CLI."""

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

METADATA = {
    "name": "p2rank",
    "display_name": "P2Rank",
    "category": "interactions",
    "description": "Predict ligand-binding sites on protein structures",
    "modal_function_name": "p2rank_worker",
    "modal_app_name": "p2rank-api",
    "status": "available",
    "outputs": {
        "predictions_csv_filepath": "Binding site predictions with scores and coordinates",
        "residues_csv_filepath": "Per-residue binding probability scores",
    },
}

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("p2rank")
    def run_p2rank(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file",
            exists=True,
        ),
        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: random 4-letter code)",
        ),
    ):
        """
        Predict ligand-binding sites on a protein structure using P2Rank.

        P2Rank uses machine learning to identify potential binding pockets.
        Output includes binding site predictions with scores, coordinates, and
        associated residues.

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

        # Read PDB content
        pdb_content = pdb.read_text()
        console.print(f"Read structure from {pdb}")

        # Build params - use pdb_content for CLI mode
        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.name,
        }

        if job_name:
            params["job_name"] = job_name

        # Execute
        run_tool_with_progress("p2rank", params, output)
