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

namespace vibeqc::tensor {

// Registered column-major FP64 lowering of mnij,mnab -> ijab, beta=1.
// The method owns the SGWB spin integration, tau, W and residual coefficients.
// This leaf reuses the admitted Eigen packing/kernel boundary from #805.
class OccupiedLadderPlan {
    View w_, tau_, residual_;
    const Budget budget_;
    Budget::Reservation control_;
    std::unique_ptr<IndexProgram> program_;
    std::uint64_t w_version_, tau_version_;
    std::size_t oo_, vv_;
    bool ordered_;
    mutable std::size_t calls_=0;
    std::size_t pack(std::size_t n) const {
        return ordered_ ? 0 : mul(std::min(n,mo_detail::gemm_tile),std::min(oo_,mo_detail::gemm_tile));
    }
public:
    OccupiedLadderPlan(Tile w, Tile tau, Tile residual, SourceStamp expected,
                       Domain occupied, Domain virtuals, NumericalMode mode)
        : w_(w.values),tau_(tau.values),residual_(residual.values),budget_(w_.allocation()->budget),
          control_(budget_.reserve(sizeof(OccupiedLadderPlan)+3*sizeof(Lease)+sizeof(Array<double>))),
          w_version_(w_.allocation()->version),tau_version_(tau_.allocation()->version),
          oo_(mul(occupied.extent,occupied.extent)),vv_(mul(virtuals.extent,virtuals.extent)),
          ordered_(mode==NumericalMode::preserve_order) {
        same_source(expected,w);same_source(expected,tau);same_source(expected,residual);
        if(mode!=NumericalMode::preserve_order && mode!=NumericalMode::reassociated_fp64)
            throw std::invalid_argument("unsupported occupied ladder numerical mode");
        auto validate=[&](const View& v,Domain second_pair) {
            const auto cols=second_pair.extent;
            if(!budget_.same(v.allocation()->budget) || v.rank()!=4 || v.conjugate() ||
               v.allocation()->type!=DType::fp64 ||
               !(v.axis(0).domain==occupied) || !(v.axis(1).domain==occupied) ||
               !(v.axis(2).domain==second_pair) || !(v.axis(3).domain==second_pair) ||
               v.axis(0).stride!=signed_size(occupied.extent) || v.axis(1).stride!=1 ||
               v.axis(2).stride!=signed_size(mul(cols,oo_)) || v.axis(3).stride!=signed_size(oo_))
                throw std::invalid_argument("occupied ladder domain/layout mismatch");
        };
        validate(w_,occupied);validate(tau_,virtuals);validate(residual_,virtuals);
        if(w_.access()==Access::write || tau_.access()==Access::write || residual_.access()!=Access::read_write)
            throw std::invalid_argument("occupied ladder access mismatch");
        if(w_.overlaps(residual_) || tau_.overlaps(residual_) ||
           w_.allocation()==residual_.allocation() || tau_.allocation()==residual_.allocation())
            throw std::invalid_argument("occupied ladder input/output alias");
        program_=std::make_unique<IndexProgram>(budget_,w_,std::vector<std::size_t>{0,1,2,3},
            tau_,std::vector<std::size_t>{0,1,4,5},residual_,std::vector<std::size_t>{2,3,4,5});
    }
    const char* kernel() const { return "cpu.eigen.occupied-ladder.fp64.v1"; }
    std::size_t calls() const { return calls_; }
    std::size_t workspace_bytes() const {
        return !oo_ || !vv_ || ordered_ ? 0 : mul(add(add(pack(oo_),pack(vv_)),
            2*mo_detail::alignment/sizeof(double)),sizeof(double));
    }
    void execute() const {
        Lease left(w_.allocation(),false),right(tau_.allocation(),false);
        if(w_version_!=w_.allocation()->version || tau_version_!=tau_.allocation()->version)
            throw std::runtime_error("stale occupied ladder inputs");
        // All admission and allocations precede the first residual write.
        Array<double> scratch(budget_,workspace_bytes()/sizeof(double));
        Lease output(residual_.allocation(),true);
        if(oo_ && vv_) {
            auto* a=ordered_?nullptr:mo_detail::aligned(scratch.data());
            auto* b=ordered_?nullptr:mo_detail::aligned(a+pack(oo_));
            mo_detail::product<Eigen::RowMajor,Eigen::ColMajor,Eigen::ColMajor>(oo_,vv_,oo_,
                static_cast<const double*>(w_.allocation()->base)+w_.offset(),oo_,
                static_cast<const double*>(tau_.allocation()->base)+tau_.offset(),oo_,
                static_cast<double*>(residual_.allocation()->base)+residual_.offset(),oo_,a,b,ordered_);
        }
        ++calls_;
    }
};

// Pack sizing shared by panel preparation and the virtual ladder.
// The output is column-major; both live packs precede the first numeric write.
namespace ladder_detail {
inline std::size_t pack_size(std::size_t extent, std::size_t depth) {
    return mul(std::min(extent,mo_detail::gemm_tile),std::min(depth,mo_detail::gemm_tile));
}
inline std::size_t pack_bytes(std::size_t m,std::size_t n,std::size_t k,bool ordered) {
    if (!m || !n || !k || ordered) return 0;
    return mul(add(add(pack_size(m,k),pack_size(n,k)),2*mo_detail::alignment/sizeof(double)),sizeof(double));
}
template<int A,int B> void product(const Budget& budget,std::size_t m,std::size_t n,std::size_t k,
        const double* a,std::size_t lda,const double* b,std::size_t ldb,double* c,std::size_t ldc,
        double alpha=1.) {
    if (!m || !n || !k) return;
    auto control=budget.reserve(sizeof(Array<double>));
    Array<double> scratch(budget,pack_bytes(m,n,k,false)/sizeof(double));
    auto* pa=mo_detail::aligned(scratch.data());
    auto* pb=mo_detail::aligned(pa+pack_size(m,k));
    mo_detail::product<A,B,Eigen::ColMajor>(m,n,k,a,lda,b,ldb,c,ldc,pa,pb,false,alpha);
}

// A packed column-major matrix of ordered pairs (xy,zt).
inline std::vector<Axis> axes(Domain x,Domain y,Domain z,Domain t) {
    auto xy=mul(x.extent,y.extent);
    return {{x,signed_size(y.extent)},{y,1},{z,signed_size(mul(t.extent,xy))},{t,signed_size(xy)}};
}
inline Domain window(Domain v,std::size_t begin,std::size_t count) {
    if (v.selection || begin>v.extent || count>v.extent-begin)
        throw std::invalid_argument("virtual ladder requires an ordered affine subrange");
    return Domain::range(v.space,count,add(v.begin,mul(begin,v.step)),v.step,v.parent,v.parent_coordinate);
}
inline void require_map(const View& view,const Budget& budget,const std::vector<Axis>& axes) {
    if (!budget.same(view.allocation()->budget) || view.rank()!=axes.size() ||
        view.allocation()->type!=DType::fp64 || view.conjugate())
        throw std::invalid_argument("virtual ladder storage mismatch");
    for (std::size_t i=0;i<axes.size();++i)
        if (!(view.axis(i).domain==axes[i].domain) || view.axis(i).stride!=axes[i].stride)
            throw std::invalid_argument("virtual ladder axis or stride mismatch");
}
} // namespace ladder_detail

// ijef,abef -> ijab, beta=1. The caller supplies the complete residual;
// the plan derives its only writable window from the authoritative a range.
class VirtualLadderPlan {
    View tau_,w_,out_;
    Budget budget_;
    Budget::Reservation control_;
    std::unique_ptr<IndexProgram> program_;
    std::uint64_t tv_,wv_;
    std::size_t oo_,ab_,ef_;
    bool ordered_;
public:
    VirtualLadderPlan(Tile tau,Tile w,Tile residual,SourceStamp expected,Domain o,Domain v,
            std::size_t begin,std::size_t count,NumericalMode mode)
        : tau_(tau.values),w_(w.values),out_(residual.values),budget_(tau_.allocation()->budget),
          control_(budget_.reserve(sizeof(VirtualLadderPlan)+3*sizeof(Lease)+sizeof(Array<double>)+4*sizeof(Axis))),
          tv_(tau_.allocation()->version),wv_(w_.allocation()->version),oo_(mul(o.extent,o.extent)),
          ab_(mul(count,v.extent)),ef_(mul(v.extent,v.extent)),ordered_(mode==NumericalMode::preserve_order) {
        same_source(expected,tau); same_source(expected,w); same_source(expected,residual);
        const auto a=ladder_detail::window(v,begin,count);
        ladder_detail::require_map(tau_,budget_,ladder_detail::axes(o,o,v,v));
        ladder_detail::require_map(out_,budget_,ladder_detail::axes(o,o,v,v));
        ladder_detail::require_map(w_,budget_,ladder_detail::axes(a,v,v,v));
        if ((!ordered_ && mode!=NumericalMode::reassociated_fp64) || tau_.access()==Access::write ||
            w_.access()==Access::write || out_.access()!=Access::read_write)
            throw std::invalid_argument("virtual ladder access or numerical mode mismatch");
        if (out_.overlaps(tau_) || out_.overlaps(w_) || out_.allocation()==tau_.allocation() ||
            out_.allocation()==w_.allocation()) throw std::invalid_argument("virtual ladder output alias");
        out_=View(out_.allocation(),ladder_detail::axes(o,o,a,v),
            signed_add(out_.offset(),signed_size(mul(mul(begin,v.extent),oo_))),Access::read_write);
        program_=std::make_unique<IndexProgram>(budget_,tau_,std::vector<std::size_t>{0,1,2,3},
            w_,std::vector<std::size_t>{4,5,2,3},out_,std::vector<std::size_t>{0,1,4,5});
    }
    const char* kernel() const { return "cpu.eigen.virtual-ladder.fp64.v1"; }
    std::size_t workspace_bytes() const { return ladder_detail::pack_bytes(oo_,ab_,ef_,ordered_); }
    void execute() const {
        Lease tau(tau_.allocation(),false),w(w_.allocation(),false);
        if (tv_!=tau_.allocation()->version || wv_!=w_.allocation()->version)
            throw std::runtime_error("stale virtual ladder inputs");
        Array<double> scratch(budget_,workspace_bytes()/sizeof(double));
        Lease output(out_.allocation(),true);
        if (!oo_ || !ab_ || !ef_) return;
        auto* pa=ordered_?nullptr:mo_detail::aligned(scratch.data());
        auto* pb=ordered_?nullptr:mo_detail::aligned(pa+ladder_detail::pack_size(oo_,ef_));
        mo_detail::product<Eigen::ColMajor,Eigen::RowMajor,Eigen::ColMajor>(oo_,ab_,ef_,
            static_cast<const double*>(tau_.allocation()->base)+tau_.offset(),oo_,
            static_cast<const double*>(w_.allocation()->base)+w_.offset(),ab_,
            static_cast<double*>(out_.allocation()->base)+out_.offset(),oo_,pa,pb,ordered_);
    }
};
} // namespace vibeqc::tensor
