#!/usr/bin/env python3
"""
Modal deployment management script.

This script uses environment variables to control deployment type and runs modal deploy.

The script will automatically detect the prefix and manage dev/prod deployments.
To use this script, your modal file must:
1. Deploy with `*-dev` or `*-prod` suffixes.
2. Import from deployment_utils: `from suno_utils.worker.deployment_utils import get_app_name`
3. Set APP_NAME using: `APP_NAME = get_app_name("your-prefix")`

The script will automatically detect the prefix and manage dev/prod deployments.

Usage: python deploy_modal.py <file_path>
"""

import sys
from pathlib import Path

from modal_deployment_shared import (
    find_app_name_prefix,
    find_repo_root,
    restore_deployment_utils,
    run_modal_command,
    update_deployment_utils,
    uses_deployment_utils,
)


def main():
    if len(sys.argv) != 2:
        print("Usage: python deploy_modal.py <file_path>")
        sys.exit(1)

    file_path = Path(sys.argv[1])

    # Handle both absolute and relative paths
    if not file_path.is_absolute():
        file_path = Path.cwd() / file_path

    if not file_path.exists():
        print(f"Error: File {file_path} does not exist")
        sys.exit(1)

    # Find the repository root (directory containing suno_utils package)
    repo_root = find_repo_root()

    print(f"Deploying {file_path}")

    # Read file content to determine app name
    content = file_path.read_text()

    # Check if file uses the centralized deployment system
    if not uses_deployment_utils(content):
        print(f"Error: {file_path} doesn't use the centralized deployment system")
        print("File should import from suno_utils.worker.deployment_utils")
        sys.exit(1)

    # Find the app name prefix
    app_prefix = find_app_name_prefix(content)
    if not app_prefix:
        print(f"Error: Could not determine app name prefix from {file_path}")
        sys.exit(1)

    # Show current and target app names
    dev_app_name = f"{app_prefix}-dev"
    prod_app_name = f"{app_prefix}-prod"

    print(f"App prefix: {app_prefix}")
    print(f"DEV app name: {dev_app_name}")
    print(f"PROD app name: {prod_app_name}")

    # Show deployment options
    print("\nDeployment options:")
    print(f"1. Deploy to DEV - APP_NAME: {dev_app_name}")
    print(f"2. Deploy to PROD - APP_NAME: {prod_app_name}")

    choice = input("\nSelect deployment type (1 for dev, 2 for prod): ").strip()

    if choice == "1":
        deployment_type = "dev"
        app_name = dev_app_name
        print(f"→ Deploying to DEV with APP_NAME: {app_name}")

        # Confirm app name
        response = input(f"\nConfirm APP_NAME '{app_name}' is correct (y/N): ").strip().lower()
        if response not in ["y", "yes"]:
            print("Deployment cancelled.")
            sys.exit(0)

    elif choice == "2":
        deployment_type = "prod"
        app_name = prod_app_name
        print(f"→ Deploying to PROD with APP_NAME: {app_name}")
        print("⚠️  WARNING: This will deploy to PRODUCTION environment! ⚠️")
        print("🚨 PRODUCTION DEPLOYMENT - This affects live users! 🚨")

        # Confirm app name
        response = input(f"\nConfirm APP_NAME '{app_name}' is correct (y/N): ").strip().lower()
        if response not in ["y", "yes"]:
            print("Deployment cancelled.")
            sys.exit(0)

        # Final confirmation for prod - require typing 'prod'
        response = input("\n🔄 Type 'prod' to confirm PRODUCTION deployment: ").strip()
        if response != "prod":
            print("Deployment cancelled.")
            sys.exit(0)
    else:
        print("Invalid choice. Deployment cancelled.")
        sys.exit(0)

    # Update deployment_utils.py with static deployment type
    env_label = "PROD" if deployment_type == "prod" else "DEV"
    print(f"\nUpdating deployment_utils.py with static {env_label} configuration...")

    try:
        # Update deployment_utils.py and store original content for rollback
        original_content = update_deployment_utils(repo_root, deployment_type)
        print(f"Updated _STATIC_DEPLOYMENT_TYPE to '{deployment_type}'")

        print(f"\nRunning modal deploy ({env_label})...")
        print("=" * 60)

        # Run modal deploy command
        return_code = run_modal_command(
            command="deploy",
            file_path=file_path,
            repo_root=repo_root,
        )

        print("=" * 60)
        if return_code != 0:
            print(f"Modal deploy failed with return code {return_code}")
        else:
            print(f"Modal deploy succeeded! ({env_label})")

        print("Deployment process complete.")

    finally:
        # Restore original deployment_utils.py content
        if "original_content" in locals():
            restore_deployment_utils(repo_root, original_content)
            print("Restored deployment_utils.py to original state")

    sys.exit(return_code)


if __name__ == "__main__":
    main()
