//
//  HomeAllFunctionsBuilder.swift
//  suixinkan
//
//  Created by Codex on 2026/6/30.
//

import Foundation

/// 「全部功能」页菜单快照，包含完整列表及按常用 URI 拆分后的分区。
struct HomeAllFunctionsSnapshot: Equatable {
    let allFunctions: [HomeMenuItem]
    let commonFunctions: [HomeMenuItem]
    let moreFunctions: [HomeMenuItem]
}

/// 「全部功能」页菜单构建器，与 Android `AllFunctionsViewModel` 对齐。
enum HomeAllFunctionsBuilder {
    /// 从顶层权限构建全部功能列表，并按常用 URI 精确拆分为常用/更多。
    static func build(
        topLevelPermissions: [PermissionItem],
        commonURIs: [String]
    ) -> HomeAllFunctionsSnapshot {
        let allFunctions = allMenuItems(from: topLevelPermissions)
        let commonSet = Set(commonURIs)
        let commonFunctions = allFunctions.filter { commonSet.contains($0.uri) }
        let moreFunctions = allFunctions.filter { !commonSet.contains($0.uri) }

        HomeAllFunctionsDiagnostics.log(snapshot: HomeAllFunctionsSnapshot(
            allFunctions: allFunctions,
            commonFunctions: commonFunctions,
            moreFunctions: moreFunctions
        ))

        return HomeAllFunctionsSnapshot(
            allFunctions: allFunctions,
            commonFunctions: commonFunctions,
            moreFunctions: moreFunctions
        )
    }

    /// 将顶层权限转为 menuList 白名单内的菜单项，保持 API 返回顺序。
    private static func allMenuItems(from topLevelPermissions: [PermissionItem]) -> [HomeMenuItem] {
        topLevelPermissions.compactMap { item -> HomeMenuItem? in
            let uri = item.uri.trimmingCharacters(in: .whitespacesAndNewlines)
            guard !uri.isEmpty, HomeCommonMenuStore.androidHomeMenuURIs.contains(uri) else {
                return nil
            }
            let fallbackTitle = item.name.isEmpty ? HomeMenuRouter.title(for: uri) : item.name
            return HomeMenuItem(
                title: HomeMenuRouter.displayTitle(for: uri, fallback: fallbackTitle),
                uri: uri,
                iconSrc: item.iconSrc
            )
        }
    }
}
