using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using System;
using System.IO;

public class BuildScript
{
    private static string[] GetScenes()
    {
        var scenes = new string[EditorBuildSettings.scenes.Length];
        for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
        {
            scenes[i] = EditorBuildSettings.scenes[i].path;
        }
        return scenes;
    }

    [MenuItem("Build/Build Android APK")]
    public static void BuildAndroid()
    {
        string outputPath = GetOutputPath();
        BuildAndroidTo(outputPath);
    }

    public static void BuildAndroidCI()
    {
        // Called from command line
        string outputPath = GetCommandLineArg("-outputPath");
        if (string.IsNullOrEmpty(outputPath))
        {
            outputPath = Path.Combine(Directory.GetCurrentDirectory(), "Builds", "Android", "MosisVR.apk");
        }

        BuildAndroidTo(outputPath);
    }

    private static void BuildAndroidTo(string outputPath)
    {
        // Ensure output directory exists
        string outputDir = Path.GetDirectoryName(outputPath);
        if (!Directory.Exists(outputDir))
        {
            Directory.CreateDirectory(outputDir);
        }

        Debug.Log($"Building Android APK to: {outputPath}");

        // Configure Android settings - export as Gradle project for manual build
        EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
        EditorUserBuildSettings.buildAppBundle = false;
        PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
        PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64;

        BuildPlayerOptions buildOptions = new BuildPlayerOptions
        {
            scenes = GetScenes(),
            locationPathName = outputPath,
            target = BuildTarget.Android,
            options = BuildOptions.None
        };

        BuildReport report = BuildPipeline.BuildPlayer(buildOptions);
        BuildSummary summary = report.summary;

        if (summary.result == BuildResult.Succeeded)
        {
            Debug.Log($"Build succeeded: {summary.totalSize} bytes, {summary.totalTime}");
        }
        else if (summary.result == BuildResult.Failed)
        {
            Debug.LogError("Build failed!");
            EditorApplication.Exit(1);
        }
    }

    private static string GetOutputPath()
    {
        // Default output path for menu builds
        return Path.Combine(Directory.GetCurrentDirectory(), "Builds", "Android", "MosisVR.apk");
    }

    private static string GetCommandLineArg(string name)
    {
        string[] args = Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == name && i + 1 < args.Length)
            {
                return args[i + 1];
            }
        }
        return null;
    }
}
