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

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

The script will automatically detect the prefix and set the deployment type for running.
To use this script, your modal file must:
1. Use `*-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")`

Usage: python run_modal.py <file_path> [additional_args...]
"""

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 run_modal.py <file_path> [additional_args...]")
        sys.exit(1)

    file_path = Path(sys.argv[1])
    # Capture any additional arguments to pass to modal run
    additional_args = sys.argv[2:]

    # 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"Running {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)

    # Always use dev for running (to avoid "Deployment type not set" error)
    deployment_type = "dev"
    app_name = f"{app_prefix}-{deployment_type}"

    print(f"App prefix: {app_prefix}")
    print(f"Running with APP_NAME: {app_name}")

    return_code = 1  # Default to error in case of exception

    try:
        # Update deployment_utils.py and store original content for rollback
        original_content = update_deployment_utils(repo_root, deployment_type)

        print("\nRunning modal run...")
        print("=" * 60)

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

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

        print("Run process complete.")

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

    sys.exit(return_code)


if __name__ == "__main__":
    main()
