"""Setup environment for deterministic audits."""

import logging
import os
from pathlib import Path

import typer

from glassalpha.cli.exit_codes import ExitCode

logger = logging.getLogger(__name__)


def setup_env(
    shell: str = typer.Option(
        None,
        help="Shell type: bash, zsh, fish. Auto-detects if not specified.",
    ),
    output: Path = typer.Option(
        None,
        "--output",
        "-o",
        help="Write environment file instead of printing to stdout",
    ),
):
    """Generate environment setup commands for deterministic audits.

    This command outputs shell commands to set required environment variables
    for byte-identical, reproducible audit generation.

    Required for compliance: Regulators require byte-identical outputs for
    audit verification. These environment variables ensure deterministic behavior.

    Examples:
        # Print commands for current shell
        glassalpha setup-env

        # Save to file and source
        glassalpha setup-env --output .glassalpha-env
        source .glassalpha-env

        # Use in current shell (bash/zsh)
        eval "$(glassalpha setup-env)"

        # Specific shell syntax
        glassalpha setup-env --shell fish > glassalpha.fish
        source glassalpha.fish

    """
    # Auto-detect shell if not specified
    if shell is None:
        shell_path = Path(os.environ.get("SHELL", "/bin/bash"))
        shell = shell_path.name
        typer.echo(f"# Auto-detected shell: {shell}", err=True)

    # Define environment variables
    env_vars = {
        "PYTHONHASHSEED": "0",
        "TZ": "UTC",
        "MPLBACKEND": "Agg",
        "SOURCE_DATE_EPOCH": "1577836800",
        # Single-threaded execution for determinism
        "OMP_NUM_THREADS": "1",
        "MKL_NUM_THREADS": "1",
        "OPENBLAS_NUM_THREADS": "1",
        "NUMEXPR_NUM_THREADS": "1",
        "VECLIB_MAXIMUM_THREADS": "1",
        "BLIS_NUM_THREADS": "1",
        # GlassAlpha-specific
        "GLASSALPHA_DETERMINISTIC": "1",
        # Locale
        "LC_ALL": "C",
    }

    # Generate shell-specific export commands
    lines = []
    lines.append("# GlassAlpha Determinism Environment")
    lines.append("# Generated by: glassalpha setup-env")
    lines.append("# Why: Ensures byte-identical audit outputs for regulatory compliance")
    lines.append("")

    if shell in ("bash", "zsh", "sh"):
        for key, value in env_vars.items():
            lines.append(f'export {key}="{value}"')
        lines.append("")
        lines.append("echo '✅ Determinism environment configured'")

    elif shell == "fish":
        for key, value in env_vars.items():
            lines.append(f"set -x {key} {value}")
        lines.append("")
        lines.append("echo '✅ Determinism environment configured'")

    elif shell in ("cmd", "powershell", "pwsh"):
        typer.secho("❌ Windows shells not yet supported", fg=typer.colors.RED, err=True)
        typer.echo("", err=True)
        typer.echo("Workaround: Set environment variables manually:", err=True)
        for key, value in env_vars.items():
            typer.echo(f"  set {key}={value}", err=True)
        raise typer.Exit(ExitCode.USER_ERROR)

    else:
        typer.secho(f"❌ Unknown shell: {shell}", fg=typer.colors.RED, err=True)
        typer.echo("", err=True)
        typer.echo("Supported shells: bash, zsh, fish", err=True)
        typer.echo("", err=True)
        typer.echo("Use --shell to specify:", err=True)
        typer.echo("  glassalpha setup-env --shell bash", err=True)
        raise typer.Exit(ExitCode.USER_ERROR)

    # Output to file or stdout
    content = "\n".join(lines)

    if output:
        output.write_text(content + "\n")
        typer.secho(f"✅ Environment file created: {output}", fg=typer.colors.GREEN, err=True)
        typer.echo("", err=True)
        typer.echo("To activate:", err=True)
        typer.echo(f"  source {output}", err=True)
    else:
        typer.echo(content)
        typer.echo("", err=True)
        typer.echo("# To use in current shell:", err=True)
        typer.echo('#   eval "$(glassalpha setup-env)"', err=True)
