#!/usr/bin/env python3
"""Load Slack secrets from Google Secret Manager.

This script demonstrates how to load secrets from GCP Secret Manager
and use them in your Nexus application.

Prerequisites:
    pip install google-cloud-secret-manager

Usage:
    # Load secrets and print
    python scripts/load_secrets_from_gcp.py

    # Load secrets and export to environment
    eval $(python scripts/load_secrets_from_gcp.py --export)

    # Load secrets and write to .env file
    python scripts/load_secrets_from_gcp.py --output .env
"""

import argparse
import sys


def get_secret(project_id: str, secret_id: str) -> str:
    """Get secret value from Google Secret Manager.

    Args:
        project_id: GCP project ID
        secret_id: Secret identifier

    Returns:
        Secret value as string

    Raises:
        Exception: If secret cannot be retrieved
    """
    try:
        from google.cloud import secretmanager
    except ImportError:
        print("Error: google-cloud-secret-manager not installed", file=sys.stderr)
        print("Install with: pip install google-cloud-secret-manager", file=sys.stderr)
        sys.exit(1)

    try:
        # Create the Secret Manager client
        client = secretmanager.SecretManagerServiceClient()

        # Build the resource name
        name = f"projects/{project_id}/secrets/{secret_id}/versions/latest"

        # Access the secret version
        response = client.access_secret_version(request={"name": name})

        # Return the decoded secret
        return response.payload.data.decode("UTF-8")

    except Exception as e:
        print(f"Error retrieving secret {secret_id}: {e}", file=sys.stderr)
        raise


def load_slack_secrets(project_id: str) -> dict[str, str]:
    """Load all Slack secrets from Google Secret Manager.

    Args:
        project_id: GCP project ID

    Returns:
        Dictionary of secret key-value pairs
    """
    secrets = {
        "NEXUS_OAUTH_SLACK_CLIENT_ID": "nexus-slack-client-id",
        "NEXUS_OAUTH_SLACK_CLIENT_SECRET": "nexus-slack-client-secret",
        "SLACK_APP_ID": "nexus-slack-app-id",
        "SLACK_SIGNING_SECRET": "nexus-slack-signing-secret",
        "SLACK_VERIFICATION_TOKEN": "nexus-slack-verification-token",
    }

    result = {}
    for env_var, secret_id in secrets.items():
        try:
            value = get_secret(project_id, secret_id)
            result[env_var] = value
            print(f"✓ Loaded: {env_var}", file=sys.stderr)
        except Exception as e:
            print(f"✗ Failed to load: {env_var} - {e}", file=sys.stderr)

    return result


def main():
    parser = argparse.ArgumentParser(description="Load Slack secrets from Google Secret Manager")
    parser.add_argument(
        "--project",
        help="GCP project ID (default: from gcloud config)",
    )
    parser.add_argument(
        "--export",
        action="store_true",
        help="Output as export commands for shell evaluation",
    )
    parser.add_argument(
        "--output",
        help="Write secrets to file (e.g., .env)",
    )
    args = parser.parse_args()

    # Get project ID
    project_id = args.project
    if not project_id:
        try:
            import subprocess

            result = subprocess.run(
                ["gcloud", "config", "get-value", "project"],
                capture_output=True,
                text=True,
                check=True,
            )
            project_id = result.stdout.strip()
        except Exception:
            print("Error: Could not determine GCP project ID", file=sys.stderr)
            print("Set with: gcloud config set project YOUR_PROJECT_ID", file=sys.stderr)
            sys.exit(1)

    print(f"Using project: {project_id}", file=sys.stderr)
    print("", file=sys.stderr)

    # Load secrets
    secrets = load_slack_secrets(project_id)

    if not secrets:
        print("\nNo secrets loaded!", file=sys.stderr)
        sys.exit(1)

    print(f"\n✓ Loaded {len(secrets)} secrets", file=sys.stderr)

    # Output based on mode
    if args.export:
        # Export mode - output shell commands
        for key, value in secrets.items():
            print(f"export {key}='{value}'")
    elif args.output:
        # File output mode
        with open(args.output, "w") as f:
            f.write("# Slack App Credentials (from Google Secret Manager)\n")
            f.write("# Generated by: scripts/load_secrets_from_gcp.py\n\n")
            for key, value in secrets.items():
                f.write(f'{key}="{value}"\n')
        print(f"\n✓ Written to: {args.output}", file=sys.stderr)
    else:
        # Default mode - pretty print
        print("\nSecrets:", file=sys.stderr)
        for key, value in secrets.items():
            # Mask secret values for display
            masked = value[:10] + "..." if len(value) > 10 else value
            print(f"  {key}={masked}", file=sys.stderr)


if __name__ == "__main__":
    main()
