import os
import shutil

from django.core.management.base import BaseCommand, CommandError
from wagtail.models import Site

from ...services import generate_capacitor_project, get_settings_for_site


class Command(BaseCommand):
    help = "Run conservative local Android verification checks for a generated mobile app shell."

    def add_arguments(self, parser):
        parser.add_argument("--site-id", type=int, required=True)

    def handle(self, *args, **options):
        site = Site.objects.filter(pk=options["site_id"]).first()
        if site is None:
            raise CommandError("Site not found.")

        output_dir = generate_capacitor_project(
            site,
            get_settings_for_site(site),
            include_platform_dirs=True,
        )
        required_paths = [
            output_dir / "package.json",
            output_dir / "capacitor.config.ts",
            output_dir / "dist" / "index.html",
            output_dir / "assets" / "branding.json",
            output_dir / "assets" / "icon-192.png",
            output_dir / "assets" / "icon-512.png",
        ]
        for path in required_paths:
            status = "OK" if path.exists() else "MISSING"
            self.stdout.write(f"[{status}] {path}")

        for executable in ["node", "npm", "npx", "java", "adb", "sdkmanager"]:
            resolved = shutil.which(executable)
            status = "OK" if resolved else "MISSING"
            self.stdout.write(f"[{status}] {executable}: {resolved or 'not found'}")

        android_home = os.environ.get("ANDROID_HOME", "")
        android_sdk_root = os.environ.get("ANDROID_SDK_ROOT", "")
        self.stdout.write(f"[INFO] ANDROID_HOME={android_home or '(unset)'}")
        self.stdout.write(f"[INFO] ANDROID_SDK_ROOT={android_sdk_root or '(unset)'}")
        self.stdout.write(f"[INFO] Generated app shell: {output_dir}")
        self.stdout.write(
            "[INFO] Next steps: npm install && npx cap add android && npx cap sync android && npx cap doctor android"
        )
