#if UNITY_OPENHARMONY
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
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);
    }

    /**
     * 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