"""Allocation and capability contract for the experimental dense DMRG route.

This is input/resource metadata, not an MPS/MPO implementation.  The current
solver diagonalizes a fixed-(N, ms2) sector of a dense full-Fock matrix.
"""

from math import comb
from numbers import Integral

DMRG_BACKEND = "dense-exact-fixed-sector"
DMRG_MAX_SPATIAL_ORBITALS = 6


class DMRGCapabilityError(ValueError):
    """The requested orbital space is unsupported by the installed backend."""


def require_dmrg_spin_orbitals(n_spin: int) -> None:
    """Keep the same limit at preflight and the final allocation boundary."""
    if n_spin > 2 * DMRG_MAX_SPATIAL_ORBITALS:
        raise DMRGCapabilityError(
            f"DMRG backend {DMRG_BACKEND} (experimental dense toy): "
            f"{n_spin} spin-orbitals requires a 2^{n_spin}x2^{n_spin} "
            f"full-Fock matrix (8 * 2**{2 * n_spin} bytes). "
            f"Maximum is {2 * DMRG_MAX_SPATIAL_ORBITALS} spin-orbitals "
            f"({DMRG_MAX_SPATIAL_ORBITALS} spatial). "
            "A scalable MPS/MPO backend is not implemented; increasing the "
            "memory budget or bond dimension does not enable this request. "
            "No active-space or method substitution was made."
        )


def dense_dmrg_space(n_orb, n_elec, ms2, active_space=None):
    """Resolve only an explicitly requested CAS; validate before allocation.

    The inactive doubly occupied core follows Hamiltonian.active_space().
    Its orbital-degeneracy check still belongs to the actual MO provider.
    """
    def integer(value, name):
        if isinstance(value, bool) or not isinstance(value, Integral):
            raise ValueError(f"DMRG {name} must be an integer, got {value!r}")
        return int(value)

    n_orb = integer(n_orb, "orbital count")
    n_elec = integer(n_elec, "electron count")
    if n_orb < 1 or not 0 <= n_elec <= 2 * n_orb:
        raise ValueError("DMRG requires a positive orbital count and 0 <= N <= 2*norb")
    if active_space is not None:
        if len(active_space) != 2:
            raise ValueError("DMRG active_space must be (n_orbitals, n_electrons)")
        active_orb, active_elec = (
            integer(active_space[0], "active orbital count"),
            integer(active_space[1], "active electron count"),
        )
        inactive = n_elec - active_elec
        if not 1 <= active_orb <= n_orb or not 0 <= active_elec <= 2 * active_orb:
            raise ValueError("DMRG active_space orbital/electron counts are out of range")
        if inactive < 0 or inactive % 2 or inactive // 2 + active_orb > n_orb:
            raise ValueError("DMRG active_space needs an even inactive count and a fitting core")
        n_orb, n_elec = active_orb, active_elec
    if ms2 is not None:
        ms2 = integer(ms2, "ms2")
        if (n_elec + ms2) % 2 or not (
            0 <= (n_elec + ms2) // 2 <= n_orb
            and 0 <= (n_elec - ms2) // 2 <= n_orb
        ):
            raise ValueError(f"DMRG sector (N={n_elec}, ms2={ms2}) does not fit {n_orb} orbitals")
    require_dmrg_spin_orbitals(2 * n_orb)
    return n_orb, n_elec, ms2


def dense_dmrg_memory(n_basis, n_elec, ms2, active_space=None):
    """Conservative byte counts for one solver, independent of CPU count.

    Include the full-Fock matrix, selected-sector copy, LAPACK copy/work,
    index construction, spin-integral conversion/permutation, and full-basis
    AO-to-MO intermediates.  The caller adds the SCF reference and process
    baseline.  These are allocation bounds, not measured peak RSS.
    """
    n_orb, n_elec, ms2 = dense_dmrg_space(n_basis, n_elec, ms2, active_space)
    n_spin = 2 * n_orb
    full_dim = 1 << n_spin
    sector = (
        comb(n_spin, n_elec) if ms2 is None else
        comb(n_orb, (n_elec + ms2) // 2) * comb(n_orb, (n_elec - ms2) // 2)
    )
    return {
        "DMRG dense full-Fock Hamiltonian": 8 * full_dim**2,
        # H_n plus an eigensolver input copy and conservative square work.
        "DMRG fixed-sector matrix + eigensolver work": 8 * (4 * sector**2 + 32 * sector),
        # Python integer/list and ndarray index storage, rounded upward.
        "DMRG sector indices": 64 * full_dim,
        # Retain originals when an explicit orbital permutation makes copies.
        "DMRG spin-orbital integral buffers": 2 * 8 * (n_spin**4 + n_spin**2),
        # AO input, MO output, contraction intermediate and packing allowance.
        # This remains full-basis even when the final solver uses a small CAS.
        "DMRG AO-to-MO integral buffers": 4 * 8 * (n_basis**4 + n_basis**2),
    }
