#pragma once

#include <pxr/usd/usd/stage.h>
#include <pxr/usd/sdf/layer.h>
#include <string>
#include <vector>
#include <memory>

namespace UsdLayerManager {

struct LayerInfo {
    pxr::SdfLayerHandle layer;
    std::string identifier;
    std::string displayName;
    std::string realPath;
    bool isMuted;
    bool isAnonymous;
    bool isRootLayer;
    bool isSessionLayer;
    bool isEditTarget;
    bool isDirty;
};

class LayerManager {
public:
    LayerManager();
    ~LayerManager();
    
    void SetStage(pxr::UsdStageRefPtr stage);
    void Refresh();
    
    // Layer information
    std::vector<LayerInfo> GetLayerStack() const;
    std::vector<LayerInfo> GetSublayers() const;
    int GetLayerCount() const { return static_cast<int>(m_layers.size()); }
    
    // Layer operations
    bool CreateSublayer(const std::string& identifier, int index = -1);
    bool InsertSublayerPath(const std::string& path, int index = -1);
    bool RemoveSublayer(int index);
    bool MoveSublayerUp(int index);
    bool MoveSublayerDown(int index);
    
    // Edit target
    bool SetEditTarget(const std::string& identifier);

    // Create a new USD file on disk, insert as sublayer, and activate as edit target.
    bool CreateNewSublayer(const std::string& absolutePath);

    // Muting
    void MuteLayer(const std::string& layerIdentifier);
    void UnmuteLayer(const std::string& layerIdentifier);
    bool IsLayerMuted(const std::string& layerIdentifier) const;
    
    // Utility
    static std::string ExtractDisplayName(const std::string& identifier);
    
private:
    void BuildLayerList();

    pxr::UsdStageRefPtr m_stage;
    std::vector<LayerInfo> m_layers;
    // Strong references keep sublayers alive even when the stage drops them after muting.
    std::vector<pxr::SdfLayerRefPtr> m_layerRefs;
};

} // namespace UsdLayerManager