import sys
import argparse
from .utils import print_header, print_footer, print_info, print_success, print_error, prompt, GRAY, RESET, CYAN, BOLD
from .detector import detect_project
from .capacitor import setup_capacitor, apply_configuration
from .config import save_local_config, load_local_config
from .github import push_and_build, check_status, download_apk
import time
from .ai import scan_codebase_for_permissions
from .capacitor import install_plugins

def init_project():
    project_info = detect_project()
    category = project_info.get("category", "web")
    proj_type = project_info.get("type", "unknown")
    
    save_local_config({"category": category, "project_type": proj_type})

    if category == "web":
        web_dir = prompt("Confirm web build directory", project_info["webDir"])
        platform_choice = prompt("Select platform (android, ios, both)", "android").lower()
        if platform_choice == "both": platforms = ["android", "ios"]
        elif platform_choice == "ios": platforms = ["ios"]
        else: platforms = ["android"]
        
        save_local_config({"webDir": web_dir, "platform": platform_choice})
        setup_capacitor(web_dir, platforms)
        
        # --- AI PERMISSION SYSTEM (FIXED) ---
        print("")
        detected_features = scan_codebase_for_permissions()
        if detected_features:
            print_success(f"AI detected {len(detected_features)} native features required by your code:")
            
            # This is the loop I accidentally deleted!
            for data in detected_features.values():
                print(f"  {CYAN}●{RESET} {data['feature']} {GRAY}({data['desc']}){RESET}")
                
            apply_ai = prompt("Auto-configure these native permissions?", "y").lower()
            if apply_ai in ['y', 'yes']:
                install_plugins(list(detected_features.keys()))
                print_success("Native permissions and plugins configured securely.")
            else:
                print_info("Skipped auto-configuration.")
        else:
            print_info("AI scan complete. No special native permissions detected.")
        # ------------------------------------

    else:
        print_info(f"Native {proj_type} project detected. Bypassing Capacitor setup.")
        platform_choice = prompt("Select platform to build in cloud (android, ios, both)", "android").lower()
        save_local_config({"platform": platform_choice})

    print_success("Ready to send to the AppForge Cloud Builder.")

def configure_project():
    config = load_local_config()
    print_info("Interactive Configuration")
    app_name = prompt("App name", config.get("appName", "My App"))
    package_id = prompt("Package ID", config.get("packageId", "com.example.app"))
    icon_path = prompt("Icon path (local PNG)", config.get("iconPath", ""))
    splash_img = prompt("Splash image (local PNG)", config.get("splashImg", ""))
    splash_bg = prompt("Splash background color (HEX)", config.get("splashBg", "#ffffff"))

    new_config = {
        "appName": app_name,
        "packageId": package_id,
        "iconPath": icon_path,
        "splashImg": splash_img,
        "splashBg": splash_bg
    }
    save_local_config(new_config)

    web_dir = config.get("webDir", "dist")
    apply_configuration(app_name, package_id, icon_path, splash_img, splash_bg, web_dir)
    return new_config

def display_app_details(config):
    print(f"{BOLD}App Configuration:{RESET}")
    print(f"  {GRAY}Name:{RESET}          {config.get('appName', 'Not set')}")
    print(f"  {GRAY}Package ID:{RESET}    {config.get('packageId', 'Not set')}")
    print(f"  {GRAY}Web Directory:{RESET} {config.get('webDir', 'Not set')}")
    print(f"  {GRAY}Icon:{RESET}          {config.get('iconPath', 'Not set')}")
    print(f"  {GRAY}Splash Image:{RESET}  {config.get('splashImg', 'Not set')}")
    print(f"  {GRAY}Splash Color:{RESET}  {config.get('splashBg', 'Not set')}")
    print("-" * 30)

def build_app():
    config = load_local_config()
    if not config:
        print_error("Project not initialized. Run 'appforge init' first.")

    app_name = config.get("appName")
    package_id = config.get("packageId")
    platform = config.get("platform", "android")
    config_was_updated = False

    if not app_name or not package_id:
        print_info("Some required app details are missing. Let's set them up.")
        new_app_name = prompt("App name", app_name or "My App")
        new_package_id = prompt("Package ID", package_id or "com.example.app")
        new_platform = prompt("Platform (android, ios, both)", platform)

        config['appName'] = new_app_name
        config['packageId'] = new_package_id
        config['platform'] = new_platform.lower()
        config_was_updated = True

    if config_was_updated:
        save_local_config(config)
        apply_configuration(
            config['appName'], config['packageId'], config.get('iconPath'),
            config.get('splashImg'), config.get('splashBg'), config.get('webDir')
        )
        print_success("App details updated.\n")

    print_info("Ready to build with the following configuration:")
    display_app_details(config)
    print(f"  {GRAY}Target Platform:{RESET} {config.get('platform', 'android')}\n")

    action = prompt("Proceed with build? (Y/n)", default="y").lower()

    if action in ['y', 'yes', '']:
        # Pass the platform to the push_and_build function!
        push_and_build(config)
        print_success("Your app is now building in the cloud!")
        print_info("Run 'appforge status' to check its progress.")
    else:
        print_info("Build cancelled.")

def status_check():
    check_status()

def download_app():
    download_apk()

def show_argu():
    print("Commands:")
    print("  appforge init       - Initialize an AppForge project")
    print("  appforge configure  - Open interactive settings")
    print("  appforge build      - Package project and send to build repo")
    print("  appforge status     - Check build status")
    print("  appforge download   - Download the built APK")
    print("  appforge help       - Show this help message")

def show_help():
    """The animated welcome sequence for the very first run."""
    welcome_message = f"{BOLD}▲ AppForge{RESET} - The Universal App Builder"
    
    # Typing animation
    for char in welcome_message:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.05)
    print("\n")
    time.sleep(0.5)
    
    print_success("Installation complete!")
    print_info("Welcome to the AppForge ecosystem.")
    
    print("\nGetting Started:")
    print("  1. `cd` into your project directory")
    print("  2. Run `appforge init` to begin\n")
    
    show_argu()
    sys.exit(0)

def main():
    print_header()
    
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("command", nargs="?", default="help", help="Command to run")
    args = parser.parse_args()

    try:
        if args.command == "init":
            init_project()
        elif args.command == "configure":
            configure_project()
        elif args.command == "build":
            build_app()
        elif args.command == "status":
            status_check()
        elif args.command == "download":
            download_app()
        else:
            show_help()
    finally:
        print_footer()

if __name__ == "__main__":
    main()
