"""SASA (Solvent Accessible Surface Area) analysis tool for the Amina CLI."""

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

METADATA = {
    "name": "sasa",
    "display_name": "SASA",
    "category": "analysis",
    "description": "Calculate solvent accessible surface area of protein structures",
    "modal_function_name": "sasa_worker",
    "modal_app_name": "sasa-analysis-api",
    "status": "available",
    "outputs": {
        "atom_csv_filepath": "Per-atom SASA values in CSV format",
        "residue_csv_filepath": "Per-residue SASA values in CSV format",
    },
}

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("sasa")
    def run_sasa(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file containing protein structure",
            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)",
        ),
        no_csv: bool = typer.Option(
            False,
            "--no-csv",
            help="Skip generating CSV output files",
        ),
    ):
        """
        Calculate Solvent Accessible Surface Area (SASA) of protein structures.

        Uses the Shrake-Rupley algorithm to compute per-atom and per-residue
        solvent accessible surface areas.

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

        # Read PDB file content
        pdb_content = pdb.read_text()
        console.print(f"Read PDB file: {pdb.name}")

        # Build params dict matching worker's expected fields
        params = {
            "pdb_content": pdb_content,
            "savecsv": not no_csv,
        }

        if job_name:
            params["job_name"] = job_name

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