import os
import json
import shutil
import subprocess
from .utils import print_success, print_error, print_info, run_with_spinner

def run_cmd(command, hide_output=True):
    try:
        stdout = subprocess.DEVNULL if hide_output else None
        subprocess.run(command, shell=True, check=True, stdout=stdout, stderr=stdout)
    except subprocess.CalledProcessError as e:
        error_message = f"Command '{command}' failed. Please check your setup."
        print_error(error_message)


def generate_capacitor_config(app_name, package_id, web_dir):
    config = {
      "appId": package_id,
      "appName": app_name,
      "webDir": web_dir,
      "server": {
        "androidScheme": "https"
      }
    }
    with open("capacitor.config.json", "w") as f:
        json.dump(config, f, indent=2)

def setup_capacitor(web_dir, platforms=["android"]):
    if not os.path.exists("package.json"):
        run_with_spinner(lambda: run_cmd("npm init -y"), "Initializing npm project")
    
    run_with_spinner(lambda: run_cmd("npm install @capacitor/core"), "Installing Capacitor Core")
    run_with_spinner(lambda: run_cmd("npm install -D @capacitor/cli"), "Installing Capacitor CLI")
    
    app_name = "Generated App"
    package_id = "com.appforge.generated"
    generate_capacitor_config(app_name, package_id, web_dir)
    print_success("Config generated (capacitor.config.json)")

    if not os.path.exists(web_dir):
        os.makedirs(web_dir)
        if os.path.exists("index.html"):
            shutil.copy("index.html", os.path.join(web_dir, "index.html"))
        else:
            with open(os.path.join(web_dir, "index.html"), "w") as f:
                f.write("<h1>AppForge Built App</h1>")

    # Add selected platforms
    if "android" in platforms:
        run_with_spinner(lambda: run_cmd("npm install @capacitor/android"), "Installing Android dependencies")
        if not os.path.exists("android"):
            run_with_spinner(lambda: run_cmd("npx cap add android", hide_output=True), "Adding native Android platform")
            
    if "ios" in platforms:
        run_with_spinner(lambda: run_cmd("npm install @capacitor/ios"), "Installing iOS dependencies")
        if not os.path.exists("ios"):
            run_with_spinner(lambda: run_cmd("npx cap add ios", hide_output=True), "Adding native iOS platform")

def apply_configuration(app_name, package_id, icon_path, splash_img, splash_bg, web_dir):
    generate_capacitor_config(app_name, package_id, web_dir)
    print_success(f"Config updated for '{app_name}'")
    
    if icon_path and os.path.exists(icon_path):
        print_success("Icon path saved")
    
    if splash_img and os.path.exists(splash_img):
        print_success("Splash image path saved")
    
    if splash_bg:
        print_success(f"Splash background color set to {splash_bg}")

def install_plugins(plugins_list):
    if not plugins_list:
        return
        
    for plugin in plugins_list:
        run_with_spinner(
            lambda p=plugin: run_cmd(f"npm install {p}", hide_output=True), 
            f"Installing native plugin: {plugin}"  # <-- FIXED THIS LINE
        )
