"""Active Site Verifier tool for the Amina CLI."""

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

METADATA = {
    "name": "activesite-verifier",
    "display_name": "Active Site Verifier",
    "category": "utilities",
    "description": "Verify presence and alignment of active-site residues in protein sequences",
    "modal_function_name": "activesite_verifier_worker",
    "modal_app_name": "activesite-verifier-api",
    "status": "available",
    "outputs": {},  # This tool produces no output files, only returns verification results
}

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("activesite-verifier")
    def run_activesite_verifier(
        sequence: Optional[str] = typer.Option(
            None,
            "--sequence",
            "-s",
            help="Direct protein sequence (standard amino acid letters A-Y)",
        ),
        fasta: Optional[Path] = typer.Option(
            None,
            "--fasta",
            "-f",
            help="Path to FASTA file containing protein sequence",
            exists=True,
        ),
        pdb: Optional[Path] = typer.Option(
            None,
            "--pdb",
            "-p",
            help="Path to PDB file containing protein structure",
            exists=True,
        ),
        active_sites: List[str] = typer.Option(
            ...,
            "--active-site",
            "-a",
            help="Active site position to verify (can be specified multiple times). "
            "Formats: 'HIS57', 'H57', 'A:CYS30', 'CYS30:A', 'C:30'",
        ),
        output: Path = typer.Option(
            ...,
            "--output",
            "-o",
            help="Output directory for results (verification results saved as JSON)",
        ),
        job_name: Optional[str] = typer.Option(
            None,
            "--job-name",
            "-j",
            help="Custom job name for tracking (default: auto-generated)",
        ),
    ):
        """
        Verify presence and alignment of active-site residues in protein sequences.

        Supports automatic shift detection for numbering mismatches between
        sequence positions and expected active site positions.

        Input can be provided as:
        - Direct sequence string (--sequence)
        - FASTA file (--fasta)
        - PDB file (--pdb)

        Active sites should be specified in one of these formats:
        - One-letter code: HIS57, H57, C30
        - Three-letter code: CYS30, HIS57
        - With chain ID: A:CYS30, A:H57, C30:A
        - Separated: C:30, H:57

        Examples:
            # Verify catalytic triad in a sequence
            amina run activesite-verifier -s "MKFL..." -a HIS57 -a ASP102 -a SER195 -o ./output/

            # Verify active sites from a FASTA file
            amina run activesite-verifier -f ./enzyme.fasta -a C30 -a H57 -o ./output/

            # Verify active sites in a PDB file with chain IDs
            amina run activesite-verifier -p ./structure.pdb -a A:HIS57 -a A:ASP102 -o ./output/
        """
        # Validate that exactly one input source is provided
        input_count = sum([sequence is not None, fasta is not None, pdb is not None])
        if input_count == 0:
            console.print("[red]Error:[/red] Must provide one of: --sequence, --fasta, or --pdb")
            raise typer.Exit(1)
        if input_count > 1:
            console.print("[red]Error:[/red] Only one input source allowed. Provide --sequence, --fasta, OR --pdb")
            raise typer.Exit(1)

        # Validate active sites are provided
        if not active_sites:
            console.print("[red]Error:[/red] At least one --active-site / -a is required")
            raise typer.Exit(1)

        # Build params dict
        params = {
            "active_site_list": list(active_sites),
        }

        # Add the input source
        if sequence:
            params["sequence"] = sequence
        elif fasta:
            params["fasta_content"] = fasta.read_text()
            params["fasta_filename"] = fasta.name
        elif pdb:
            params["pdb_content"] = pdb.read_text()
            params["pdb_filename"] = pdb.name

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("activesite-verifier", params, output)
