#if UNITY_OPENHARMONY
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using System;

public class ComboSDKOpenHarmonyPostBuild : IPostprocessBuildWithReport
{
    public int callbackOrder
    {
        get { return 10; }
    }

    /**
    * build 构建完成后回调
    */
    public void OnPostprocessBuild(BuildReport report)
    {
        if (report.summary.platform == BuildTarget.OpenHarmony)
        {
            Debug.Log("Path is :" + report.summary.outputPath);
            CustomRecodeFile(report.summary.outputPath);
        }
    }

    private void CustomRecodeFile(string path)
    {
        ModifyMainWorker(path);
        // HTTPDNS 桥：把 Unity 包内的 cpp/ets 母本复制到导出工程 entry 模块。
        // 其余装配（entry/build-profile.json5 加 externalNativeOptions、ComboSDKAbility 接 setupHttpDnsBridge 调用）由 Combo CLI 处理。
        CopyHttpDnsBridge(path);
    }

    /**
     * 复制 HTTPDNS 桥的 cpp/ets 母本到导出工程：
     *   Combo/Plugins/OpenHarmony/cpp/{HttpDnsBridge.cpp,CMakeLists.txt} -> entry/src/main/cpp/
     *   Combo/Plugins/OpenHarmony/ets/HttpDnsBridge.ets                  -> entry/src/main/ets/
     */
    private void CopyHttpDnsBridge(string exportPath)
    {
        var packageRoot = GetCurrentPackageRoot("com.seayoo.sdk");
        if (string.IsNullOrEmpty(packageRoot))
        {
            Debug.LogError("[ComboSDK] OpenHarmonyPostBuilder: 无法定位 SDK 包根，跳过 HTTPDNS 桥复制");
            return;
        }

        var srcRoot = Path.Combine(packageRoot, "Combo/Plugins/OpenHarmony");
        var entryMain = Path.Combine(exportPath, "entry", "src", "main");

        CopyFileInto(Path.Combine(srcRoot, "cpp/HttpDnsBridge.cpp"), Path.Combine(entryMain, "cpp"));
        CopyFileInto(Path.Combine(srcRoot, "cpp/CMakeLists.txt"),   Path.Combine(entryMain, "cpp"));
        CopyFileInto(Path.Combine(srcRoot, "ets/HttpDnsBridge.ets"), Path.Combine(entryMain, "ets"));
    }

    // 复制单个文件到目标目录（目录不存在则创建；覆盖同名文件）。
    private void CopyFileInto(string srcFile, string destDir)
    {
        if (!File.Exists(srcFile))
        {
            Debug.LogError($"[ComboSDK] OpenHarmonyPostBuilder: HTTPDNS 桥母本不存在 {srcFile}");
            return;
        }
        Directory.CreateDirectory(destDir);
        var destFile = Path.Combine(destDir, Path.GetFileName(srcFile));
        File.Copy(srcFile, destFile, true);
        Debug.Log($"[ComboSDK] OpenHarmonyPostBuilder: 复制 HTTPDNS 桥\n  {srcFile}\n  -> {destFile}");
    }

    // 经 UPM API 定位 SDK 包根目录（resolvedPath）。
    private static string GetCurrentPackageRoot(string packageName)
    {
        ListRequest listRequest = Client.List();
        while (!listRequest.IsCompleted) { }

        if (listRequest.Status == StatusCode.Success)
        {
            var packageInfo = listRequest.Result.FirstOrDefault(p => p.name == packageName);
            if (packageInfo != null)
            {
                return packageInfo.resolvedPath;
            }
            Debug.LogError($"[ComboSDK] OpenHarmonyPostBuilder: 未找到包 '{packageName}'");
        }
        return null;
    }

    /**
     * WorkerProxy.ets 文件中新增import和初始化方法调用
     */
    private void ModifyMainWorker(string path)
    {
        // 修改 WorkerProxy.ets
        var filePath = path + "/tuanjieLib/src/main/ets/workers/WorkerProxy.ets";
        if (!File.Exists(filePath))
        {
            Debug.LogError("WorkerProxy.ets 文件不存在！");
            return;
        }

        // 插入 import
        var importLine = "import { ComboSDKOpenHarmonyManager } from '../ComboSDKOpenHarmonyManager';";
        InsertImports(filePath, importLine);

        // 插入 ComboSDKOpenHarmonyManager.InitMessageBind(this.threadWorker); 到构造函数末尾
        var initLine = "    ComboSDKOpenHarmonyManager.InitMessageBind(this.threadWorker);";
        InsertInConstructor(filePath, initLine);
    }

    // 在构造函数末尾插入初始化代码
    private void InsertInConstructor(string filePath, string initLine)
    {
        if (!File.Exists(filePath) || string.IsNullOrEmpty(initLine))
        {
            Debug.LogError("文件不存在或初始化内容为空！");
            return;
        }

        string[] codes = File.ReadAllLines(filePath);
        int constructorEndIndex = -1;
        int constructorStartIndex = -1;
        int openBraces = 0;

        for (int i = 0; i < codes.Length; i++)
        {
            string line = codes[i].Trim();

            // 判断是否是构造函数，记录起始位置
            if (line.StartsWith("private constructor("))
            {
                constructorStartIndex = i;
                openBraces = 1; // 初始化开括号计数
                continue;
            }

            // 如果在构造函数内部，追踪花括号
            if (constructorStartIndex != -1)
            {
                if (line.Contains("{"))
                    openBraces++;
                if (line.Contains("}"))
                    openBraces--;

                // 判断尾部结束点
                if (openBraces == 0)
                {
                    constructorEndIndex = i;
                    break;
                }
            }
        }

        if (constructorStartIndex == -1 || constructorEndIndex == -1)
        {
            Debug.LogError("未找到构造函数！");
            return;
        }

        // 向构造函数的最终部分插入内容
        InsertAfterIndex(filePath, codes, constructorEndIndex - 1, new string[] { initLine });
    }

    // 在文件中添加import行内容
    public static void InsertImports(string filePath, string importLine)
    {
        if (!File.Exists(filePath) || string.IsNullOrEmpty(importLine))
        {
            Debug.LogError("文件不存在或导入内容为空！");
            return;
        }

        string[] codes = File.ReadAllLines(filePath);
        if (codes.Length == 0 || Array.Exists(codes, line => line.Contains(importLine)))
        {
            return;
        }

        int firstImportLine = 0;
        for (int i = 0; i < codes.Length; i++)
        {
            string str = codes[i];
            if (str.StartsWith("import") && str.EndsWith(";"))
            {
                firstImportLine = i;
                break;
            }
        }

        InsertAfterIndex(filePath, codes, firstImportLine, new string[] { importLine });
    }

    // 在指定索引之后插入内容
    public static void InsertAfterIndex(string filePath, string[] codes, int insertAfterIndex, string[] contentLines)
    {
        if (codes.Length == 0 || contentLines.Length == 0)
        {
            Debug.LogError("代码或内容为空！");
            return;
        }

        int newCodesLineCount = codes.Length + contentLines.Length;
        string[] newCodes = new string[newCodesLineCount];
        for (int i = newCodesLineCount - 1; i >= 0; i--)
        {
            if (i > insertAfterIndex + contentLines.Length)
            {
                newCodes[i] = codes[i - contentLines.Length];
                continue;
            }

            if (i > insertAfterIndex)
            {
                newCodes[i] = contentLines[i - insertAfterIndex - 1];
                continue;
            }

            newCodes[i] = codes[i];
        }

        File.WriteAllLines(filePath, newCodes);
    }
}
#endif