"""EMNgly N-linked glycosylation prediction tool for the Amina CLI."""

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

METADATA = {
    "name": "emngly",
    "display_name": "EMNGly",
    "category": "interactions",
    "description": "N-linked glycosylation site prediction using ESM-1b + MIF + SVM",
    "modal_function_name": "emngly_pred_worker",
    "modal_app_name": "emngly-pred-api",
    "status": "available",
    "outputs": {
        "csv_filepath": "CSV file with all prediction 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("emngly")
    def run_emngly(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB structure file",
            exists=True,
        ),
        threshold: float = typer.Option(
            0.5,
            "--threshold",
            "-t",
            help="Prediction threshold (0.0-1.0, higher = more stringent)",
            min=0.0,
            max=1.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 output files (default: random 4-letter code)",
        ),
    ):
        """
        Predict N-linked glycosylation sites from protein structures.

        Uses EMNgly method: ESM-1b embeddings + MIF structural embeddings + SVM classifier.
        Identifies potential N-X-S/T motifs and predicts glycosylation probability.

        Examples:
            amina run emngly --pdb ./1A2J.pdb -o ./output/
            amina run emngly --pdb ./structure.pdb --threshold 0.7 -o ./output/
            amina run emngly --pdb ./1A2J.pdb -j myjob -o ./output/
        """
        # 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()

        params = {
            "pdb_content": pdb_content,
            "input_filename": pdb.stem,  # e.g., "1A2J" from "1A2J.pdb"
            "threshold": threshold,
        }

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("emngly", params, output)
