#include "dynamic_endpoints.h"

#include <app/util/attribute-storage.h>        // DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN 等
#include <app/util/af-types.h>                 // EmberAfEndpointType
#include <app/util/endpoint-config-api.h>      // emberAfSetDynamicEndpoint()
#include <lib/support/logging/CHIPLogging.h>
#include <../default_zap/zap-generated/endpoint_config.h> // EmberAfDeviceType
#include <../default_zap/zap-generated/CHIPClusters.h>
#include <lib/core/CHIPError.h>
#include <lib/support/Span.h>

#include <app-common/zap-generated/ids/Commands.h>
#include <app-common/zap-generated/attributes/Accessors.h>
// #include <app-common/zap-generated/cluster-objects.h>
#include <app/clusters/switch-server/switch-server.h>

using namespace chip;
using namespace chip::app;

// 描述符数组字段最大长度
static constexpr uint16_t kDescriptorArrayMax = 254;
// NodeLabel/VendorName 等字符串的最大长度（随需调整）
static constexpr uint16_t kNodeLabelSize = 32;
static constexpr uint16_t kVendorNameSize = 32;
static constexpr uint16_t kProductNameSize = 32;

namespace
{
// -------------------- 属性表 --------------------

// Descriptor cluster
DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(descriptorAttrs)
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::DeviceTypeList::Id, ARRAY,   kDescriptorArrayMax, 0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::ServerList::Id,     ARRAY,   kDescriptorArrayMax, 0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::ClientList::Id,     ARRAY,   kDescriptorArrayMax, 0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::PartsList::Id,      ARRAY,   kDescriptorArrayMax, 0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::FeatureMap::Id,     BITMAP32, 4,                  0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Descriptor::Attributes::ClusterRevision::Id, INT16U, 2, 0), // ★ 新增
DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();

// BasicInformation cluster (常用的最小子集)
// DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(basicAttrs)
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::BasicInformation::Attributes::NodeLabel::Id,
//                               CHAR_STRING, kNodeLabelSize, ZAP_ATTRIBUTE_MASK(WRITABLE)),
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::BasicInformation::Attributes::VendorName::Id,
//                               CHAR_STRING, kVendorNameSize, 0),
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::BasicInformation::Attributes::ProductName::Id,
//                               CHAR_STRING, kProductNameSize, 0),
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::BasicInformation::Attributes::FeatureMap::Id,
//                               BITMAP32, 4, 0),
// DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();

// Identify cluster
DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(identifyAttrs)
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Identify::Attributes::IdentifyTime::Id, INT16U, 2, ZAP_ATTRIBUTE_MASK(WRITABLE)),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Identify::Attributes::IdentifyType::Id,  ENUM8, 1, 0),
    DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Identify::Attributes::FeatureMap::Id,  BITMAP32, 4, 0),
DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();

// Switch cluster
// DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(switchAttrs)
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::NumberOfPositions::Id, INT8U,   1, 0),
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::CurrentPosition::Id,   INT8U,   1, 0),
//     DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::FeatureMap::Id,      BITMAP32,  4, 0),
// DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();


DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(switchAttrs)
DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::NumberOfPositions::Id,
                            INT8U, 1, 0),   // default = 2, 初始化时写
DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::CurrentPosition::Id,
                            INT8U, 1, 0),   // default = 0
DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::MultiPressMax::Id,
                            INT8U, 1, 0),   // default = 2
DECLARE_DYNAMIC_ATTRIBUTE(Clusters::Switch::Attributes::FeatureMap::Id,
                            BITMAP32, 4, 0),// default = 30 (0x1E)
DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();

// -------------------- Cluster 列表 --------------------
DECLARE_DYNAMIC_CLUSTER_LIST_BEGIN(genericSwitchClusters)
    DECLARE_DYNAMIC_CLUSTER(Clusters::Switch::Id,      switchAttrs,    ZAP_CLUSTER_MASK(SERVER), nullptr, nullptr),
    DECLARE_DYNAMIC_CLUSTER(Clusters::Descriptor::Id,  descriptorAttrs,ZAP_CLUSTER_MASK(SERVER), nullptr, nullptr),
    // DECLARE_DYNAMIC_CLUSTER(Clusters::BasicInformation::Id, basicAttrs,ZAP_CLUSTER_MASK(SERVER), nullptr, nullptr),
    DECLARE_DYNAMIC_CLUSTER(Clusters::Identify::Id,    identifyAttrs,  ZAP_CLUSTER_MASK(SERVER), nullptr, nullptr),
DECLARE_DYNAMIC_CLUSTER_LIST_END;

// -------------------- Endpoint 类型 --------------------
DECLARE_DYNAMIC_ENDPOINT(genericSwitchEndpoint, genericSwitchClusters);

// 当前 endpoint 的 cluster 数量（编译期常量）
static constexpr size_t kClusterCount =
    sizeof(genericSwitchClusters) / sizeof(genericSwitchClusters[0]);

// 允许的最大动态 endpoint 数；按你的 SKU 上限设置（例如 12）
static constexpr size_t kMaxDynamicEndpoints = 12;

// 为每个可能的动态 endpoint 预留一组 DataVersion（零初始化即可）
static DataVersion sDataVersionPool[kMaxDynamicEndpoints][kClusterCount];

// DeviceType = Generic Switch (0x000F)
static constexpr EmberAfDeviceType kGenericSwitchDeviceTypes[] = {
    { 0x000F, 1 },//Generic switch
};

} // namespace

// -------------------- Public API --------------------

void AddGenericSwitchEndpoints(int count)
{
    if (count <= 0) {
        return;
    }

    if (static_cast<size_t>(count) > kMaxDynamicEndpoints) {
        ChipLogError(AppServer, "Requested %d endpoints > kMaxDynamicEndpoints(%u), clamping.",
                     count, static_cast<unsigned>(kMaxDynamicEndpoints));
        count = static_cast<int>(kMaxDynamicEndpoints);
    }

    // EndpointId nextId = 2; // 0 = Root Node, 1 = 模板
    EndpointId nextId = 3; // 0 = Root Node, 1 = 模板
    for (int i = 0; i < count; ++i) {
        EndpointId ep = nextId++;

        // 取本 index 的 DataVersion 缓冲；确保生命周期覆盖整个运行期
        DataVersion * dv = sDataVersionPool[i]; // 已零初始化

        ChipLogProgress(AppServer, "ep %u cluster count=%u", ep,
                static_cast<unsigned>(genericSwitchEndpoint.clusterCount));

        CHIP_ERROR err = emberAfSetDynamicEndpoint(
            static_cast<uint16_t>(i),    // 动态 endpoint index
            ep,                          // endpointId
            &genericSwitchEndpoint,      // endpoint 模板
            Span<DataVersion>(dv, kClusterCount), // cluster data versions
            Span<const EmberAfDeviceType>(kGenericSwitchDeviceTypes, ArraySize(kGenericSwitchDeviceTypes)),
            kInvalidEndpointId);         // 无 parent endpoint

        if (err == CHIP_NO_ERROR) {
            ChipLogProgress(AppServer, "✅ Added GenericSwitch endpoint %u", static_cast<unsigned>(ep));

        for (size_t j = 0; j < ArraySize(switchAttrs); j++) {
    ChipLogProgress(AppServer, "SwitchAttr[%u] = 0x%08lx",
                    (unsigned) j, (unsigned long) switchAttrs[j].attributeId);
}


        // 初始化 Switch cluster 的默认值
        auto st = Clusters::Switch::Attributes::NumberOfPositions::Set(ep, 2);
        if (st != Protocols::InteractionModel::Status::Success) {
            ChipLogError(AppServer, "❌ Failed to set NumberOfPositions on ep %u (status=%u)",
                 static_cast<unsigned>(ep), static_cast<unsigned>(st));
        }
        Clusters::Switch::Attributes::CurrentPosition::Set(ep, 0);
        Clusters::Switch::Attributes::MultiPressMax::Set(ep, 2);
        Clusters::Switch::Attributes::FeatureMap::Set(ep, 30);    // 0x1E
        Clusters::Switch::Attributes::ClusterRevision::Set(ep, 2);
        // uint8_t numPos = 0;
        // Clusters::Switch::Attributes::NumberOfPositions::Get(ep, &numPos);
        // ChipLogProgress(AppServer, "Switch[%u] NumberOfPositions = %u", ep, numPos);

        uint8_t numPos = 0, curPos = 255, mpMax = 0;
        uint32_t feat = 0;
        uint16_t rev = 0;

        Clusters::Switch::Attributes::NumberOfPositions::Get(ep, &numPos);
        Clusters::Switch::Attributes::CurrentPosition::Get(ep, &curPos);
        Clusters::Switch::Attributes::MultiPressMax::Get(ep, &mpMax);
        Clusters::Switch::Attributes::FeatureMap::Get(ep, &feat);
        Clusters::Switch::Attributes::ClusterRevision::Get(ep, &rev);

        ChipLogProgress(AppServer,
            "Switch[%u] NumPos=%u CurPos=%u MultiMax=%u FeatureMap=0x%lx Rev=%u",
            ep, numPos, curPos, mpMax, static_cast<unsigned long>(feat), rev);

        } else {
            ChipLogError(AppServer, "❌ Failed to add GenericSwitch endpoint %u (err=%s)",
                         static_cast<unsigned>(ep), chip::ErrorStr(err));
        }
    }
}