"""Glycosylation Ensemble prediction tool for the Amina CLI."""

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

METADATA = {
    "name": "glycosylation-ensemble",
    "display_name": "Glycosylation Ensemble",
    "category": "interactions",
    "description": "Predict N-linked and O-linked glycosylation sites using ensemble methods",
    "modal_function_name": "glycosylation_ensemble_worker",
    "modal_app_name": "glycosylation-ensemble-api",
    "status": "available",
    "outputs": {
        "comprehensive_csv_filepath": "CSV file with all glycosylation predictions",
        "bfactor_pdb_filepath": "B-factor annotated PDB with glycosylation site scores",
    },
}

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("glycosylation-ensemble")
    def run_glycosylation_ensemble(
        # Input option
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file for glycosylation analysis",
            exists=True,
        ),
        # N-linked method options
        emngly_threshold: float = typer.Option(
            0.5,
            "--emngly-threshold",
            help="EMNgly prediction threshold (0.0-1.0)",
            min=0.0,
            max=1.0,
        ),
        lmngly_threshold: float = typer.Option(
            0.5,
            "--lmngly-threshold",
            help="LMNglyPred prediction threshold (0.0-1.0)",
            min=0.0,
            max=1.0,
        ),
        lmngly_ensemble_method: str = typer.Option(
            "average",
            "--lmngly-ensemble-method",
            help="LMNglyPred ensemble method: average or voting",
        ),
        # O-linked method options
        isoglyp_analysis_mode: str = typer.Option(
            "comprehensive",
            "--isoglyp-analysis-mode",
            help="ISOGlyP analysis mode: comprehensive, initiating_only, fill_in_only, high_confidence",
        ),
        isoglyp_context_window: str = typer.Option(
            "standard",
            "--isoglyp-context-window",
            help="ISOGlyP context window: minimal, standard, focused, extended",
        ),
        isoglyp_threshold: float = typer.Option(
            0.7,
            "--isoglyp-threshold",
            help="ISOGlyP prediction threshold (0.0-1.0)",
            min=0.0,
            max=1.0,
        ),
        # B-factor annotation
        create_bfactor_pdb: bool = typer.Option(
            True,
            "--create-bfactor-pdb/--no-bfactor-pdb",
            help="Create B-factor annotated PDB with glycosylation site scores",
        ),
        # Output options
        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 and O-linked glycosylation sites using ensemble methods.

        This tool combines multiple prediction methods for comprehensive
        glycosylation site analysis:

        N-linked Methods:
            EMNgly - ESM-1b embeddings + MIF + SVM classifier
            LMNglyPred - ProtT5 embeddings with neural networks

        O-linked Method:
            ISOGlyP - Enhancement Value Prediction (EVP) algorithm

        The ensemble provides consensus predictions for N-linked sites
        (when both EMNgly and LMNglyPred agree) and independent O-linked
        predictions from ISOGlyP.

        Examples:
            amina run glycosylation-ensemble --pdb ./protein.pdb -o ./results/
            amina run glycosylation-ensemble --pdb ./protein.pdb --emngly-threshold 0.7 -o ./results/
            amina run glycosylation-ensemble --pdb ./protein.pdb --no-bfactor-pdb -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()

        # Build params dict
        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.name,
            # N-linked method configurations
            "emngly_threshold": emngly_threshold,
            "lmngly_threshold": lmngly_threshold,
            "lmngly_ensemble_method": lmngly_ensemble_method,
            # O-linked method configuration
            "isoglyp_analysis_mode": isoglyp_analysis_mode,
            "isoglyp_context_window": isoglyp_context_window,
            "isoglyp_threshold": isoglyp_threshold,
            # B-factor annotation
            "create_bfactor_pdb": create_bfactor_pdb,
        }

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("glycosylation-ensemble", params, output)
