import argparse
import sys
import os
from .tunnel import create_tunnel
from .server_check import check_domain_availability

def main():
    parser = argparse.ArgumentParser(
        description='Vertex Web - Deploy local web apps publicly',
        epilog='Example: vertex_web app.py --domain myapp.vertexweb.dev'
    )
    
    parser.add_argument(
        'script',
        help='Python Flask script to run'
    )
    
    parser.add_argument(
        '--domain', '-d',
        help='Custom domain/subdomain (optional)'
    )
    
    parser.add_argument(
        '--port', '-p',
        type=int,
        default=5552,
        help='Port to run on (default: 5552)'
    )
    
    parser.add_argument(
        '--check', '-c',
        action='store_true',
        help='Check domain availability only'
    )
    
    args = parser.parse_args()
    
    # Check if script exists
    if not os.path.exists(args.script):
        print(f"❌ Error: Script '{args.script}' not found!")
        sys.exit(1)
    
    # If check mode
    if args.check:
        if args.domain:
            is_available = check_domain_availability(args.domain)
            if is_available:
                print(f"✅ Domain '{args.domain}' is available!")
            else:
                print(f"❌ Domain '{args.domain}' is not available!")
        else:
            print("⚠️  Please specify a domain with --domain")
        return
    
    # Start tunnel
    print(f"🔍 Checking domain availability...")
    
    if args.domain and not check_domain_availability(args.domain):
        print(f"❌ Domain '{args.domain}' is not available!")
        choice = input("Continue with random domain? (y/n): ")
        if choice.lower() != 'y':
            sys.exit(1)
        args.domain = None
    
    # Create tunnel
    success = create_tunnel(args.script, args.domain, args.port)
    
    if not success:
        sys.exit(1)

if __name__ == '__main__':
    main()