"""Interface Identifier tool for the Amina CLI."""

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

METADATA = {
    "name": "interface-identifier",
    "display_name": "Interface Identifier",
    "category": "interactions",
    "description": "Identify interface residues between chains in protein complexes",
    "modal_function_name": "interface_identifier_worker",
    "modal_app_name": "interface-identifier-api",
    "status": "available",
    "outputs": {
        "interface_bfactor_pdb_filepath": "B-factor annotated PDB for visualization (100=interface, 0=non-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("interface-identifier")
    def run_interface_identifier(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to protein complex structure (PDB or CIF file with multiple chains)",
            exists=True,
        ),
        distance_cutoff: float = typer.Option(
            8.0,
            "--distance",
            "-d",
            help="Distance cutoff in Angstroms for interface detection (default: 8.0)",
            min=3.0,
            max=15.0,
        ),
        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 tracking (default: random 4-letter code)",
        ),
    ):
        """
        Identify interface residues between chains in protein complexes.

        Analyzes a multi-chain protein structure to find residues at the interface
        between different chains. A residue is considered an interface residue if
        any of its heavy atoms are within the distance cutoff of atoms from another chain.

        The tool outputs:
        - Interface residues per chain (e.g., ["ALA45", "GLY46", ...])
        - Chain type classification (protein vs nucleic acid)
        - Interface pairs (e.g., ["A-B", "A-C"])
        - B-factor annotated PDB for visualization (100=interface, 0=non-interface)

        Note: The input structure must have at least 2 polymer chains (protein or nucleic acid).

        Examples:
            amina run interface-identifier -p complex.pdb -o ./results/
            amina run interface-identifier -p complex.cif --distance 10.0 -o ./results/
            amina run interface-identifier -p dimer.pdb -d 6.0 -j my-analysis -o ./results/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

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

        # Build params
        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.name,
            "distance_cutoff": distance_cutoff,
        }

        if job_name:
            params["job_name"] = job_name

        console.print(f"Distance cutoff: {distance_cutoff}Å")

        run_tool_with_progress("interface-identifier", params, output)
