"""Hydrophobicity analysis tool for the Amina CLI."""

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

METADATA = {
    "name": "hydrophobicity",
    "display_name": "Hydrophobicity Analysis",
    "category": "analysis",
    "description": "Analyze hydrophobic residue distribution between protein core and surface",
    "modal_function_name": "hydrophobicity_worker",
    "modal_app_name": "hydrophobicity-analysis-api",
    "status": "available",
    "outputs": {
        "csv_filepath": "Detailed hydrophobicity analysis results CSV",
        "plot_filepath": "Sigmoidal transition plot (if enabled)",
    },
}

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("hydrophobicity")
    def run_hydrophobicity(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file for analysis",
            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)",
        ),
        savecsv: bool = typer.Option(
            True,
            "--savecsv/--no-csv",
            help="Save results to CSV file",
        ),
        save_sigmoid_plot: bool = typer.Option(
            True,
            "--plot/--no-plot",
            help="Save sigmoidal transition plot",
        ),
        threshold_step: float = typer.Option(
            0.001,
            "--threshold-step",
            help="Step size for SASA threshold testing (0.0-1.0)",
        ),
        critical_distance: float = typer.Option(
            5.0,
            "--critical-distance",
            help="Max distance (Angstroms) for residue contact analysis",
        ),
    ):
        """
        Analyze hydrophobic residue distribution in a protein structure.

        Classifies residues as core or surface using SASA-based thresholds
        and analyzes hydrophobic contacts and surface exposure.

        Examples:
            amina run hydrophobicity --pdb ./protein.pdb -o ./results/
            amina run hydrophobicity --pdb ./protein.pdb -j myjob -o ./results/
            amina run hydrophobicity --pdb ./protein.pdb --no-plot -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 from {pdb}")

        # Build params matching worker's expected fields
        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.stem,  # Use filename for naming outputs
            "savecsv": savecsv,
            "save_sigmoid_plot": save_sigmoid_plot,
            "threshold_step": threshold_step,
            "critical_distance": critical_distance,
        }

        if job_name:
            params["job_name"] = job_name

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