"""PeSTo binding interface prediction tool for the Amina CLI."""

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

METADATA = {
    "name": "pesto",
    "display_name": "PeSTo",
    "category": "interactions",
    "description": "Predict protein binding interfaces for protein-protein, DNA/RNA, ion, ligand, and lipid interactions",
    "modal_function_name": "pesto_worker",
    "modal_app_name": "pesto-api",
    "status": "available",
    "outputs": {
        "interface_pdb_0": "Protein-protein interface PDB with B-factor scores",
        "interface_pdb_1": "Protein-DNA/RNA interface PDB with B-factor scores",
        "interface_pdb_2": "Protein-ion interface PDB with B-factor scores",
        "interface_pdb_3": "Protein-ligand interface PDB with B-factor scores",
        "interface_pdb_4": "Protein-lipid interface PDB with B-factor scores",
        "interface_csv_0": "Binding residue details CSV for protein-protein interface",
        "interface_csv_1": "Binding residue details CSV for protein-DNA/RNA interface",
        "interface_csv_2": "Binding residue details CSV for protein-ion interface",
        "interface_csv_3": "Binding residue details CSV for protein-ligand interface",
        "interface_csv_4": "Binding residue details CSV for protein-lipid interface",
    },
}

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("pesto")
    def run_pesto(
        # Input options
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to input PDB file",
            exists=True,
        ),
        # PeSTo parameters
        model_version: str = typer.Option(
            "i_v4_1",
            "--model-version",
            "-m",
            help="Model version (i_v3_0, i_v3_1, i_v4_0, i_v4_1)",
        ),
        binding_threshold: float = typer.Option(
            0.5,
            "--threshold",
            "-t",
            help="Probability threshold for classifying binding residues (0-1)",
            min=0.0,
            max=1.0,
        ),
        save_interfaces: bool = typer.Option(
            True,
            "--save-interfaces/--no-save-interfaces",
            help="Save separate PDB files per interface type",
        ),
        # Standard options
        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 protein binding interfaces using PeSTo (Protein Structure Transformer).

        PeSTo identifies potential interaction sites for 5 interface types:
        - Protein-protein interactions
        - Protein-DNA/RNA interactions
        - Protein-ion interactions
        - Protein-ligand interactions
        - Protein-lipid interactions

        Predictions are encoded in B-factor fields (0-100 scale) in output PDB files,
        with CSV files containing detailed binding residue information.

        Examples:
            # Basic binding interface prediction
            amina run pesto --pdb ./protein.pdb -o ./results/

            # Custom binding threshold
            amina run pesto --pdb ./protein.pdb --threshold 0.7 -o ./results/

            # Use older model version
            amina run pesto --pdb ./protein.pdb --model-version i_v3_1 -o ./results/

            # Custom job name
            amina run pesto --pdb ./protein.pdb -j myprotein -o ./results/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

        # Validate model version
        valid_versions = ["i_v3_0", "i_v3_1", "i_v4_0", "i_v4_1"]
        if model_version not in valid_versions:
            console.print(f"[red]Error:[/red] Invalid model version. Choose from: {', '.join(valid_versions)}")
            raise typer.Exit(1)

        # Read PDB content (CLI mode sends content, not path)
        pdb_content = pdb.read_text()

        # Build params
        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.name,
            "model_version": model_version,
            "binding_threshold": binding_threshold,
            "save_individual_interfaces": save_interfaces,
        }

        if job_name:
            params["job_name"] = job_name

        console.print(f"Input: {pdb.name}")
        console.print(f"Model: {model_version}, Threshold: {binding_threshold}")

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