"""Throwaway constrained 2-objective, 3-variable problem for the workflow suite.

Declares the ``CONSTRAINED`` seam: ``evaluate_constrained`` returns
``(fitness, cv, state)`` with ``cv >= 0`` and a static ``n_con = 2`` width.
Constraint 0 requires ``pop[:, 0] >= 0.5`` and constraint 1 requires
``pop[:, 1] <= 0.5``, so a population spread over [0, 1) contains both feasible
and infeasible individuals.
"""

from __future__ import annotations

import dataclasses
from typing import Any

import evoxc
import evoxc.numpy as enp
import numpy as np
from evox.core import EmptyState

__all__ = [
    "CONSTRAINED",
    "TinyConstrainedProblemConfig",
    "evaluate",
    "evaluate_constrained",
    "reference_cv",
    "reference_fitness",
]

CONSTRAINED = True
"""Module-level seam: the workflow evaluates through ``evaluate_constrained``."""


@dataclasses.dataclass(frozen=True)
class TinyConstrainedProblemConfig:
    """Static problem config; ``n_con`` is the violation width the workflow requires."""

    n_objs: int = 2
    dim: int = 3
    n_con: int = 2


def reference_fitness(pop: Any) -> np.ndarray:
    """Host-side numpy twin of the traced objectives (the tests' oracle)."""
    x = np.asarray(pop, dtype=np.float32)
    f0 = np.sum(np.square(x - np.float32(0.25)), axis=1)
    f1 = np.sum(np.square(x - np.float32(0.75)), axis=1)
    return np.stack([f0, f1], axis=1).astype(np.float32)


def reference_cv(pop: Any) -> np.ndarray:
    """Host-side numpy twin of the violations computed by :func:`evaluate_constrained`."""
    x = np.asarray(pop, dtype=np.float32)
    cv0 = np.maximum(np.float32(0.5) - x[:, 0], np.float32(0.0))
    cv1 = np.maximum(x[:, 1] - np.float32(0.5), np.float32(0.0))
    return np.stack([cv0, cv1], axis=1).astype(np.float32)


def _objective(pop: Any) -> Any:
    """Traced ``(n, 2)`` objective; shared by both evaluation entry points."""
    low = evoxc.ops.constant(evoxc.core.tensor(np.asarray(0.25, np.float32)))
    high = evoxc.ops.constant(evoxc.core.tensor(np.asarray(0.75, np.float32)))
    return enp.stack([enp.sum(enp.square(pop - low), axis=1), enp.sum(enp.square(pop - high), axis=1)], axis=1)


def evaluate(config: TinyConstrainedProblemConfig, state: Any, pop: Any) -> tuple[Any, Any]:
    """Objective-only evaluation (still required by the component resolution convention)."""
    return _objective(pop), EmptyState()


def evaluate_constrained(config: TinyConstrainedProblemConfig, state: Any, pop: Any) -> tuple[Any, Any, Any]:
    """Traced constrained evaluation: ``(n, 2)`` fitness, ``(n, n_con)`` cv, unchanged state."""
    zero = evoxc.ops.constant(evoxc.core.tensor(np.asarray(0.0, np.float32)))
    half = evoxc.ops.constant(evoxc.core.tensor(np.asarray(0.5, np.float32)))
    cv0 = enp.maximum(half - pop[:, 0], zero)
    cv1 = enp.maximum(pop[:, 1] - half, zero)
    cv = enp.stack([cv0, cv1], axis=1)
    return _objective(pop), cv, EmptyState()