import os
import json
from .utils import print_info, print_warning

def detect_project():
    # 1. Detect Flutter
    if os.path.exists("pubspec.yaml"):
        print_info("Detected Flutter project")
        return {"type": "flutter", "category": "native", "webDir": None}

    # 2. Detect Native Android (Kotlin/Java)
    if os.path.exists("build.gradle") or os.path.exists("build.gradle.kts"):
        print_info("Detected Native Android (Kotlin/Java) project")
        return {"type": "android_native", "category": "native", "webDir": None}

    # 3. Detect Native iOS (Swift/Objective-C)
    if glob_exists("*.xcodeproj") or glob_exists("*.xcworkspace"):
        print_info("Detected Native iOS (Swift/Objective-C) project")
        return {"type": "ios_native", "category": "native", "webDir": None}

    # 4. Detect Web Frameworks (Needs Capacitor)
    if not os.path.exists("package.json"):
        if os.path.exists("index.html"):
            print_info("Detected plain HTML/CSS project")
            return {"type": "html", "category": "web", "webDir": "www"}
        return {"type": "unknown", "category": "web", "webDir": "www"}

    with open("package.json", "r") as f:
        try: pkg = json.load(f)
        except json.JSONDecodeError: return {"type": "unknown", "category": "web", "webDir": "www"}

    deps = pkg.get("dependencies", {})
    dev_deps = pkg.get("devDependencies", {})
    all_deps = {**deps, **dev_deps}
    scripts_str = json.dumps(pkg.get("scripts", {}))

    if "nuxt" in all_deps: return {"type": "nuxt", "category": "web", "webDir": ".output/public"}
    if "@sveltejs/kit" in all_deps: return {"type": "sveltekit", "category": "web", "webDir": "build"}
    if "@angular/core" in all_deps: return {"type": "angular", "category": "web", "webDir": "dist"}
    if "next" in all_deps: return {"type": "next", "category": "web", "webDir": "out"}
    if "vite" in all_deps or "vite build" in scripts_str: return {"type": "vite", "category": "web", "webDir": "dist"}
    if "react-scripts" in all_deps: return {"type": "react", "category": "web", "webDir": "build"}
    if "typescript" in all_deps: return {"type": "ts", "category": "web", "webDir": "dist"}
    
    return {"type": "static", "category": "web", "webDir": "build"}

def glob_exists(pattern):
    import glob
    return len(glob.glob(pattern)) > 0
