"""Show current status."""

import json
from pathlib import Path

import click
import yaml
from rich.table import Table

from ..config.settings import Settings, CONFIG_FILE
from ..display.output import console, success, error, warning, info, panel
from ..telemetry import _is_enabled as telemetry_enabled
from ..tools.git_tools import is_git_repo, get_current_branch
from ._shared import load_local_config, local_config_exists


@click.command()
def status() -> None:
    """Show Gjalla configuration status.

    Displays the current configuration status including:
    - Git repository status
    - API key configuration
    - Project mapping
    - Guardrails installation
    """
    repo_path = Path.cwd()

    panel("gjalla Status", title="gjalla status")
    console.print()

    # Build status table
    table = Table(show_header=True, header_style="bold cyan")
    table.add_column("Check", style="bold")
    table.add_column("Status")
    table.add_column("Details")

    # Check 1: Git repository
    is_git = is_git_repo(repo_path)
    if is_git:
        branch = get_current_branch(repo_path)
        table.add_row(
            "Git Repository",
            "[green]Yes[/green]",
            f"Branch: {branch}"
        )
    else:
        table.add_row(
            "Git Repository",
            "[red]No[/red]",
            "Not a git repository"
        )

    # Check 2: Global config exists
    if CONFIG_FILE.exists():
        table.add_row(
            "Global Config",
            "[green]Found[/green]",
            str(CONFIG_FILE)
        )
    else:
        table.add_row(
            "Global Config",
            "[yellow]Missing[/yellow]",
            "Run 'gjalla init' to create"
        )

    # Check 3: API key configured
    settings = Settings.load()
    if settings.api_key:
        masked_key = settings.api_key[:4] + "..." + settings.api_key[-4:] if len(settings.api_key) > 8 else "****"
        table.add_row(
            "API Key",
            "[green]Configured[/green]",
            masked_key
        )
    else:
        table.add_row(
            "API Key",
            "[red]Missing[/red]",
            "Set GJALLA_API_KEY or run 'gjalla init'"
        )

    # Check 4: Project mapping
    project_id = settings.get_project_id(repo_path)
    if project_id:
        table.add_row(
            "Project Mapping",
            "[green]Configured[/green]",
            f"Project ID: {project_id}"
        )
    else:
        table.add_row(
            "Project Mapping",
            "[yellow]Not Mapped[/yellow]",
            "Run 'gjalla init' to map this repository"
        )

    # Check 5: .gjalla project config
    old_gjalla_config = repo_path / ".gjalla"
    if local_config_exists(repo_path):
        cfg = load_local_config(repo_path)
        if cfg:
            table.add_row(
                "Project Config",
                "[green]Found[/green]",
                f".gjalla/config.yaml (project {cfg.get('project_id', '?')})"
            )
        else:
            table.add_row(
                "Project Config",
                "[yellow]Invalid[/yellow]",
                "Run 'gjalla init' to recreate"
            )
    elif old_gjalla_config.is_file():
        table.add_row(
            "Project Config",
            "[yellow]Old Format[/yellow]",
            "Run 'gjalla setup' to migrate .gjalla → .gjalla/config.yaml"
        )
    else:
        table.add_row(
            "Project Config",
            "[yellow]Missing[/yellow]",
            "Run 'gjalla init' to create .gjalla/config.yaml"
        )

    # Check 6: Guardrails installed
    pre_script = repo_path / "scripts" / "gjalla-attestation-check.sh"
    post_script = repo_path / "scripts" / "gjalla-post-commit-upload.sh"
    if pre_script.exists() and post_script.exists():
        table.add_row(
            "Guardrails",
            "[green]Installed[/green]",
            "Attestation scripts in scripts/"
        )
    elif pre_script.exists() or post_script.exists():
        table.add_row(
            "Guardrails",
            "[yellow]Partial[/yellow]",
            "Run 'gjalla setup' to complete installation"
        )
    else:
        table.add_row(
            "Guardrails",
            "[dim]Not Installed[/dim]",
            "Run 'gjalla setup' to install"
        )

    # Check 7: Telemetry
    if telemetry_enabled():
        table.add_row(
            "Telemetry",
            "[green]Enabled[/green]",
            "Anonymous usage stats"
        )
    else:
        table.add_row(
            "Telemetry",
            "[dim]Disabled[/dim]",
            "Set telemetry: true in config or GJALLA_TELEMETRY=1"
        )

    console.print(table)
    console.print()

    # Summary
    if is_git and settings.api_key and project_id and local_config_exists(repo_path):
        success("gjalla is fully configured for this repository")
    elif not is_git:
        error("Not in a git repository")
    elif not CONFIG_FILE.exists():
        warning("gjalla not initialized. Run 'gjalla init'")
    elif not settings.api_key:
        warning("API key not configured. Run 'gjalla init' or set GJALLA_API_KEY")
    elif not project_id:
        warning("Repository not mapped. Run 'gjalla init'")
