"""Verification utilities for checking telemetry in GCP services."""

from datetime import datetime, timedelta
from typing import Optional, List


def verify_cloud_logging(
    service_name: str,
    minutes_ago: int = 10,
    max_results: int = 10,
    project_id: Optional[str] = None,
) -> List[dict]:
    """Verify logs are appearing in Cloud Logging.

    Args:
        service_name: Service name to filter logs by
        minutes_ago: How many minutes back to search
        max_results: Maximum number of log entries to return
        project_id: GCP project ID (uses default if not specified)

    Returns:
        List of log entries

    Raises:
        ImportError: If google-cloud-logging is not installed
    """
    try:
        from google.cloud import logging as cloud_logging
        import google.auth
    except ImportError:
        raise ImportError(
            "google-cloud-logging not installed. Install with: pip install google-cloud-logging"
        )

    if not project_id:
        _, project_id = google.auth.default()

    logging_client = cloud_logging.Client(project=project_id)

    timestamp = (datetime.utcnow() - timedelta(minutes=minutes_ago)).isoformat() + "Z"

    filter_str = (
        f'logName="projects/{project_id}/logs/emms-model-telemetry" AND timestamp>="{timestamp}"'
    )

    if service_name:
        filter_str += f' AND labels."service.name"="{service_name}"'

    entries = list(logging_client.list_entries(filter_=filter_str, max_results=max_results))

    return entries


def print_cloud_logging_status(service_name: str, minutes_ago: int = 10):
    """Print Cloud Logging verification status in a formatted way."""
    print("Querying Cloud Logging for SDK logs...\n")
    print(f"Service: {service_name}")
    print(f"Time range: Last {minutes_ago} minutes\n")

    try:
        entries = verify_cloud_logging(service_name, minutes_ago)

        if entries:
            print(f"✓ Found {len(entries)} SDK log entries\n")
            for i, entry in enumerate(entries[:5], 1):
                print(f"{i}. {entry.payload}")
                if hasattr(entry, "labels") and entry.labels:
                    if "service.name" in entry.labels:
                        print(f"   Service: {entry.labels['service.name']}")
                    if "code.function.name" in entry.labels:
                        print(f"   Function: {entry.labels['code.function.name']}")
                print()

            print("✓ Cloud Logging export working!")
            print("\nConsole: https://console.cloud.google.com/logs/query")
            print('Filter: logName="projects/bhsf-ai-team-projects/logs/emms-model-telemetry"')
            return True
        else:
            print(f"✗ No SDK logs found for service: {service_name}\n")
            print("Possible reasons:")
            print("  1. Logs not yet propagated (wait 30-60 seconds)")
            print("  2. Service name mismatch")
            print("  3. SDK not generating logs")
            return False

    except Exception as e:
        print(f"✗ Error querying Cloud Logging: {e}")
        return False


def verify_cloud_trace(project_id: Optional[str] = None, max_traces: int = 5) -> List:
    """Verify traces are appearing in Cloud Trace.

    Args:
        project_id: GCP project ID (uses default if not specified)
        max_traces: Maximum number of traces to return

    Returns:
        List of trace summaries

    Raises:
        ImportError: If google-cloud-trace is not installed
    """
    try:
        from google.cloud import trace_v1
        import google.auth
    except ImportError:
        raise ImportError(
            "google-cloud-trace not installed. Install with: pip install google-cloud-trace"
        )

    if not project_id:
        _, project_id = google.auth.default()

    trace_client = trace_v1.TraceServiceClient()

    request = trace_v1.ListTracesRequest(project_id=project_id, page_size=max_traces)
    traces = list(trace_client.list_traces(request=request))

    return traces


def print_cloud_trace_status(project_id: Optional[str] = None):
    """Print Cloud Trace verification status in a formatted way."""
    print("Querying Cloud Trace for SDK traces...\n")

    try:
        import google.auth
        from google.cloud import trace_v1

        if not project_id:
            _, project_id = google.auth.default()

        traces = verify_cloud_trace(project_id)

        if traces:
            print(f"✓ Found {len(traces)} recent traces\n")

            trace_client = trace_v1.TraceServiceClient()

            for i, trace_summary in enumerate(traces[:3], 1):
                trace_id = trace_summary.trace_id

                try:
                    get_request = trace_v1.GetTraceRequest(project_id=project_id, trace_id=trace_id)
                    full_trace = trace_client.get_trace(request=get_request)

                    print(f"{i}. Trace {trace_id[:16]}...")
                    print(f"   Spans: {len(full_trace.spans)}")

                    if full_trace.spans:
                        for span in full_trace.spans[:3]:
                            print(f"     - {span.name}")
                    print()

                except Exception as e:
                    print(f"{i}. Trace {trace_id[:16]}... (error: {str(e)[:50]})")

            print("✓ Cloud Trace export working!")
            print("\nConsole: https://console.cloud.google.com/traces/list")
            return True
        else:
            print("✗ No traces found\n")
            print("Possible reasons:")
            print("  1. Traces not yet propagated (wait 1-2 minutes)")
            print("  2. Collector not exporting traces")
            print("  3. SDK not generating traces")
            return False

    except Exception as e:
        print(f"✗ Error querying Cloud Trace: {e}")
        return False
