"""Simple RMSD backbone analysis tool for the Amina CLI."""

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

METADATA = {
    "name": "simple-rmsd",
    "display_name": "Simple RMSD",
    "category": "analysis",
    "description": "Calculate backbone RMSD between two protein structures",
    "modal_function_name": "simple_rmsd_worker",
    "modal_app_name": "simple-rmsd-api",
    "status": "available",
    "outputs": {},  # Simple RMSD returns metrics, not files
    "output_display": {
        "sections": [
            {
                "title": "RMSD Results",
                "fields": [
                    {"key": "rmsd", "label": "Backbone RMSD", "format": "{:.4f} \u00c5"},
                    {"key": "num_atoms_aligned", "label": "Atoms aligned"},
                    {"key": "ref_chains_used", "label": "Reference chains"},
                    {"key": "mobile_chains_used", "label": "Mobile chains"},
                ],
            },
        ],
    },
}

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("simple-rmsd")
    def run_simple_rmsd(
        mobile: Path = typer.Option(
            ...,
            "--mobile",
            "-m",
            help="Path to mobile/designed structure (PDB file to be aligned)",
            exists=True,
        ),
        reference: Path = typer.Option(
            ...,
            "--reference",
            "-r",
            help="Path to reference structure (PDB file to align against)",
            exists=True,
        ),
        mobile_chains: Optional[str] = typer.Option(
            None,
            "--mobile-chains",
            help="Chains to use from mobile structure (e.g., 'A' or 'A,B'). Default: all chains",
        ),
        ref_chains: Optional[str] = typer.Option(
            None,
            "--ref-chains",
            help="Chains to use from reference structure (e.g., 'A' or 'A,B'). Default: all chains",
        ),
        output: Path = typer.Option(
            ...,
            "--output",
            "-o",
            help="Output directory for results (required for job tracking)",
        ),
        job_name: Optional[str] = typer.Option(
            None,
            "--job-name",
            "-j",
            help="Custom job name for tracking (default: random 4-letter code)",
        ),
    ):
        """
        Calculate backbone RMSD between two protein structures.

        Simple RMSD aligns backbone atoms (N, CA, C, O) from the mobile structure
        to the reference structure and computes the root mean square deviation.
        Lower RMSD values indicate more similar structures (0 = identical).

        Typical RMSD interpretations:
        - < 1.0 Å: Very similar (same fold, minor differences)
        - 1.0-2.0 Å: Similar (same fold, some loop variations)
        - 2.0-4.0 Å: Moderately similar
        - > 4.0 Å: Significantly different structures

        Examples:
            amina run simple-rmsd -m designed.pdb -r native.pdb -o ./results/
            amina run simple-rmsd -m model.pdb -r reference.pdb --mobile-chains A --ref-chains A -o ./results/
            amina run simple-rmsd -m complex.pdb -r reference.pdb --mobile-chains A,B -o ./results/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

        # Read file contents
        mobile_content = mobile.read_text()
        reference_content = reference.read_text()
        console.print(f"Read mobile structure from {mobile}")
        console.print(f"Read reference structure from {reference}")

        # Build params
        params = {
            "mobile_pdb_content": mobile_content,
            "mobile_pdb_filename": mobile.name,
            "reference_pdb_content": reference_content,
            "reference_pdb_filename": reference.name,
        }

        # Parse chain selections
        if mobile_chains:
            # Split on comma and uppercase
            chains = [c.strip().upper() for c in mobile_chains.split(",") if c.strip()]
            params["mobile_chains"] = chains
            console.print(f"Using chains from mobile structure: {chains}")

        if ref_chains:
            # Split on comma and uppercase
            chains = [c.strip().upper() for c in ref_chains.split(",") if c.strip()]
            params["ref_chains"] = chains
            console.print(f"Using chains from reference structure: {chains}")

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("simple-rmsd", params, output)
