"""PDB Quality Assessment tool for the Amina CLI."""

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

METADATA = {
    "name": "pdb-quality-assessment",
    "display_name": "PDB Quality Assessment",
    "category": "utilities",
    "description": "Analyze protein structure quality with Ramachandran plots and geometric validation",
    "modal_function_name": "pdb_quality_assessment_worker",
    "modal_app_name": "pdb-quality-assessment-api",
    "status": "available",
    "outputs": {
        "ramachandran_plot_filepath": "Ramachandran plot visualization (PNG)",
        "quality_plots_filepath": "Combined quality plots (PNG)",
        "report_filepath": "JSON quality report with detailed metrics",
    },
}

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("pdb-quality-assessment")
    def run_pdb_quality_assessment(
        pdb: Path = typer.Option(
            ...,
            "--pdb",
            "-p",
            help="Path to PDB file to analyze",
            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)",
        ),
    ):
        """
        Analyze protein structure quality through comprehensive geometric validation.

        Provides Ramachandran plot analysis, B-factor statistics, geometric validation
        metrics, and overall quality scores. Automatically detects single vs multi-chain
        structures.

        Examples:
            amina run pdb-quality-assessment --pdb ./structure.pdb -o ./results/
            amina run pdb-quality-assessment --pdb ./1ABC.pdb -j myjob -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()

        params = {
            "pdb_content": pdb_content,
            "pdb_filename": pdb.name,
        }

        if job_name:
            params["job_name"] = job_name

        run_tool_with_progress("pdb-quality-assessment", params, output)
