"""ISOGlyP O-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": "isoglyp",
    "display_name": "ISOGlyP",
    "category": "interactions",
    "description": "O-linked glycosylation site prediction using Enhancement Value Prediction",
    "modal_function_name": "isoglyp_worker",
    "modal_app_name": "isoglyp-api",
    "status": "available",
    "outputs": {
        "csv_filepath": "CSV file with glycosylation site predictions",
    },
}

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("isoglyp")
    def run_isoglyp(
        # Input options (mutually exclusive)
        sequence: Optional[str] = typer.Option(
            None,
            "--sequence",
            "-s",
            help="Protein sequence (amino acids only)",
        ),
        fasta: Optional[Path] = typer.Option(
            None,
            "--fasta",
            "-f",
            help="Path to FASTA file with single protein sequence(s)",
            exists=True,
        ),
        # Analysis options
        analysis_mode: str = typer.Option(
            "comprehensive",
            "--analysis-mode",
            "-a",
            help="Analysis mode: comprehensive, initiating_only, fill_in_only, high_confidence",
        ),
        context_window: str = typer.Option(
            "standard",
            "--context-window",
            "-c",
            help="Context window: minimal, standard, focused, extended",
        ),
        threshold: float = typer.Option(
            1.0,
            "--threshold",
            "-t",
            help="Score threshold for positive predictions (default: 1.0)",
            min=0.0,
            max=10.0,
        ),
        # 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 O-linked glycosylation sites from protein sequences.

        Uses ISOGlyP Enhancement Value Prediction algorithm to identify
        Serine (S) and Threonine (T) residues likely to be glycosylated
        by GalNAc transferases.

        Supports 11 transferases: T1, T2, T3, T4, T5, T10, T11, T12, T13, T14, T16

        Analysis Modes:
            comprehensive - All transferases (default)
            initiating_only - T1, T2, T3 (early glycosylation)
            fill_in_only - T4, T5, T10-T16 (later glycosylation)
            high_confidence - Most active transferases

        Examples:
            amina run isoglyp --sequence "MVLSPADKTNVKAAWG" -o ./results/
            amina run isoglyp --fasta ./protein.fasta -o ./results/
            amina run isoglyp --fasta ./protein.fasta --threshold 0.5 -o ./results/
            amina run isoglyp --sequence "MSTPV..." --analysis-mode initiating_only -o ./results/
        """
        # Validate required options
        if output is None:
            console.print("[red]Error:[/red] --output / -o is required")
            raise typer.Exit(1)

        # Validate mutually exclusive inputs
        if not sequence and not fasta:
            console.print("[red]Error:[/red] Provide either --sequence or --fasta")
            raise typer.Exit(1)

        if sequence and fasta:
            console.print("[red]Error:[/red] Provide only one of --sequence or --fasta")
            raise typer.Exit(1)

        # Build params dict
        params = {
            "analysis_mode": analysis_mode,
            "context_window": context_window,
            "threshold": threshold,
        }

        if sequence:
            params["sequence"] = sequence
        elif fasta:
            # Read FASTA file content and pass to worker
            fasta_content = fasta.read_text()
            params["fasta_content"] = fasta_content
            params["fasta_filename"] = fasta.name

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("isoglyp", params, output)
