// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "vibeqc/tensor/core.hpp"

namespace vibeqc::tensor {

// A bounded schedule cache, not an allocator, numeric cache or IR replacement.
// Matthews doi:10.1137/16M108968X sections 6-7; GETT doi:10.1145/3157733
// sections 3-5; Gray/Kourtis doi:10.22331/q-2021-03-15-410 section 4.7:
// cost packing/repeated work and simultaneous storage, not just FLOPs.
enum class NumericalMode { preserve_order, reassociated_fp64, compensated_complex };
enum class ScheduleKernel { per_p, panel_product, mapped_panel, compensated_pair, local_panel, affine_product };
struct Schedule {
    ScheduleKernel kernel = ScheduleKernel::per_p;
    std::size_t panel_columns = 0;
    int workers = 1;
    double per_p_seconds = 0, panel_seconds = 0;
};
struct AxisSignature {
    Space space, parent, selection;
    std::size_t parent_coordinate=0, extent=0, begin=0, step=1;
    std::ptrdiff_t stride=0;
    static AxisSignature from(const Axis& a) {
        const auto& d=a.domain;
        return {d.space,d.parent,d.selection ? d.selection->identity : Space{},
            d.parent_coordinate,d.extent,d.begin,d.step,a.stride};
    }
    bool operator==(const AxisSignature& a) const {
        return space==a.space && parent==a.parent && selection==a.selection &&
            parent_coordinate==a.parent_coordinate && extent==a.extent && begin==a.begin && step==a.step && stride==a.stride;
    }
};
// Process-local capabilities cannot accidentally hit a serialized/remote key.
// Placement changes are explicit caller tokens; no affinity or NUMA claim.
inline Space local_hardware() { static const auto token=Space::create();return token; }
inline Space local_placement() { static const auto token=Space::create();return token; }
struct StructuralKey {
    static constexpr std::size_t maximum_axes=12,maximum_operands=5;
    std::array<AxisSignature,maximum_axes> axes{};
    std::array<std::size_t,maximum_operands> ranks{},alignment{};
    std::array<std::ptrdiff_t,maximum_operands> offsets{};
    std::array<DType,maximum_operands> dtypes{};
    std::array<Access,maximum_operands> accesses{};
    std::array<bool,maximum_operands> conjugates{};
    std::size_t operands=0,axis_count=0;
    Space source,metric,frame,pattern,hardware=local_hardware(),placement=local_placement();
    std::size_t operation=0,schema_revision=1,partition=0,backend=0,planner_policy=0;
    std::size_t budget=0,execution_allowance=0,pack_limit=0,tuning_work_limit=0;
    std::size_t enumeration_limit=0,assembly_limit=0;
    NumericalMode mode=NumericalMode::preserve_order;
    int requested_workers=1,actual_workers=1,thread_policy=0,tuning_passes=0;
    bool nested=false;
    template<class S> void append_schema(const S& schema,DType type,Access access,bool conjugate=false,
                                        std::ptrdiff_t offset=0,std::size_t align=0) {
        if(operands==maximum_operands || schema.rank()>maximum_axes-axis_count)
            throw std::length_error("structural cache key capacity exceeded");
        ranks[operands]=schema.rank();dtypes[operands]=type;accesses[operands]=access;
        conjugates[operands]=conjugate;offsets[operands]=offset;alignment[operands++]=align;
        for(std::size_t i=0;i<schema.rank();++i) axes[axis_count++]=AxisSignature::from(schema.axis(i));
    }
    void append(const View& view) {
        append_schema(view,view.allocation()->type,view.access(),view.conjugate(),view.offset(),
                      reinterpret_cast<std::uintptr_t>(view.allocation()->base)%alignof(double));
    }
    bool operator==(const StructuralKey& k) const {
        if(operands!=k.operands || axis_count!=k.axis_count || source!=k.source || metric!=k.metric || frame!=k.frame || pattern!=k.pattern ||
            hardware!=k.hardware || placement!=k.placement || operation!=k.operation || schema_revision!=k.schema_revision ||
            partition!=k.partition || backend!=k.backend || planner_policy!=k.planner_policy || budget!=k.budget || execution_allowance!=k.execution_allowance ||
            enumeration_limit!=k.enumeration_limit || assembly_limit!=k.assembly_limit ||
            pack_limit!=k.pack_limit || tuning_work_limit!=k.tuning_work_limit || mode!=k.mode ||
            requested_workers!=k.requested_workers || actual_workers!=k.actual_workers || thread_policy!=k.thread_policy ||
            tuning_passes!=k.tuning_passes || nested!=k.nested) return false;
        for(std::size_t i=0;i<operands;++i)
            if(ranks[i]!=k.ranks[i] || alignment[i]!=k.alignment[i] || offsets[i]!=k.offsets[i] ||
                dtypes[i]!=k.dtypes[i] || accesses[i]!=k.accesses[i] || conjugates[i]!=k.conjugates[i])return false;
        for(std::size_t i=0;i<axis_count;++i)if(!(axes[i]==k.axes[i]))return false;
        return true;
    }
};

// Exactly one entry and no per-lookup allocation. It owns a small Budget for
// its persistent control storage. An execution imports retained_bytes() once
// in its external inventory; the cache never owns a View, provider or payload.
class StructuralCache {
    Budget budget_;
    Budget::Reservation control_;
    mutable std::mutex mutex_;
    StructuralKey key_;
    Schedule schedule_;
    bool valid_=false;
public:
    StructuralCache() : budget_(add(sizeof(StructuralCache),Budget::baseline_bytes())),
        control_(budget_.reserve(sizeof(StructuralCache))) {}
    std::size_t retained_bytes() const { return budget_.live(); }
    bool lookup(const StructuralKey& key,Schedule& schedule) const {
        std::lock_guard<std::mutex> lock(mutex_);
        if(!valid_ || !(key_==key)) return false;
        schedule=schedule_;return true;
    }
    void store(const StructuralKey& key,const Schedule& schedule) {
        std::lock_guard<std::mutex> lock(mutex_);key_=key;schedule_=schedule;valid_=true;
    }
    void clear() { std::lock_guard<std::mutex> lock(mutex_);valid_=false; }
};
} // namespace vibeqc::tensor
