"""CLI commands for releaseops telemetry."""

import json

import typer

app = typer.Typer(help="Telemetry metadata inspection and injection helpers.")


def _parse_bundle_ref(ref: str) -> tuple:
    """Parse 'bundle-id@env' format. Returns (bundle_id, env)."""
    if "@" not in ref:
        raise typer.BadParameter(
            f"Invalid bundle reference '{ref}'. "
            "Expected format: 'bundle-id@environment' (e.g., 'agent@prod')"
        )
    parts = ref.split("@", 1)
    return parts[0], parts[1]


@app.command("show")
def show_cmd(
    bundle_ref: str = typer.Argument(
        ..., help="Bundle reference (format: bundle-id@environment)"
    ),
    as_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Show telemetry metadata for a bundle."""
    from llmhq_releaseops.core.resolver import Resolver
    from llmhq_releaseops.storage.git_store import GitStore
    from llmhq_releaseops.telemetry.injector import TelemetryInjector

    store = GitStore(path)
    if not store.is_initialized():
        typer.echo("Error: ReleaseOps not initialized.", err=True)
        raise typer.Exit(1)

    try:
        bundle_id, env = _parse_bundle_ref(bundle_ref)
    except typer.BadParameter as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)

    try:
        resolver = Resolver(store)
        injector = TelemetryInjector()
        metadata = injector.extract_from_resolved_bundle(bundle_id, env, resolver)
    except (ValueError, FileNotFoundError) as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)

    if as_json:
        typer.echo(json.dumps(metadata.to_dict(), indent=2))
        return

    typer.echo("Bundle Metadata")
    typer.echo("=" * 40)
    typer.echo(f"  Bundle ID:   {metadata.bundle_id}")
    typer.echo(f"  Version:     {metadata.bundle_version}")
    typer.echo(f"  Hash:        {metadata.bundle_hash}")
    typer.echo(f"  Environment: {metadata.environment}")

    if metadata.prompt_refs:
        typer.echo("\n  Prompts:")
        for role, ref in metadata.prompt_refs.items():
            typer.echo(f"    {role} -> {ref}")

    if metadata.policy_refs:
        typer.echo("\n  Policies:")
        for role, ref in metadata.policy_refs.items():
            typer.echo(f"    {role} -> {ref}")

    if metadata.model_config:
        typer.echo("\n  Model:")
        for key, val in metadata.model_config.items():
            typer.echo(f"    {key}: {val}")

    typer.echo("\n  OpenTelemetry Attributes (flat):")
    for key, val in metadata.to_flat_dict().items():
        typer.echo(f"    {key}: {val}")


@app.command("inject")
def inject_cmd(
    bundle_ref: str = typer.Argument(
        ..., help="Bundle reference (format: bundle-id@environment)"
    ),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Output a Python code snippet for telemetry injection."""
    from llmhq_releaseops.core.resolver import Resolver
    from llmhq_releaseops.storage.git_store import GitStore
    from llmhq_releaseops.telemetry.injector import TelemetryInjector

    store = GitStore(path)
    if not store.is_initialized():
        typer.echo("Error: ReleaseOps not initialized.", err=True)
        raise typer.Exit(1)

    try:
        bundle_id, env = _parse_bundle_ref(bundle_ref)
    except typer.BadParameter as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)

    # Verify bundle exists
    try:
        resolver = Resolver(store)
        injector = TelemetryInjector()
        injector.extract_from_resolved_bundle(bundle_id, env, resolver)
    except (ValueError, FileNotFoundError) as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)

    snippet = f'''\
# Copy this code to inject telemetry:
from llmhq_releaseops.telemetry import TelemetryInjector
from llmhq_releaseops.telemetry.integrations.opentelemetry import (
    OpenTelemetryIntegration,
    inject_context,
)
from llmhq_releaseops.core.resolver import Resolver
from llmhq_releaseops.storage.git_store import GitStore

injector = TelemetryInjector()
resolver = Resolver(GitStore("."))
metadata = injector.extract_from_resolved_bundle(
    "{bundle_id}", "{env}", resolver
)

# Option A: Inject into current span
integration = OpenTelemetryIntegration()
integration.inject_current_span(metadata)

# Option B: Use context manager
with inject_context(metadata):
    agent.run()  # Your agent code here
'''
    typer.echo(snippet)
