"""Versioned scoring profiles.

A profile declares *exactly* how candidates are compared: which metrics count, how they
are normalized, how they are weighted, and what disqualifies a candidate outright. The
profile name and version are recorded on every run, so a score is always interpretable
after the fact (design map 12).

Metric definitions here are **provisional**. The scientific team owns the final set and
its thresholds; this profile exists so the scoring machinery is exercised end to end
before the real pipeline lands.
"""

import hashlib
import json
from dataclasses import dataclass, field, replace

from engine.contract import HIGHER_BETTER, LOWER_BETTER
from engine.errors import ScoringProfileError

#: What to do when a metric is missing for a candidate.
TREAT_AS_WORST = "worst"
SKIP = "skip"


@dataclass(frozen=True, slots=True)
class MetricSpec:
    """The declaration of one metric, per design map 12."""

    name: str
    direction: str
    weight: float
    valid_range: tuple[float, float]
    missing_behavior: str = TREAT_AS_WORST
    description: str = ""
    #: "kcal/mol" · "percent 0-100" · "fraction 0-1" · "log2 fold" · "linear fold" · ....
    #: Advertised via engine.contract.MetricInfo — the one piece of metadata that would
    #: have prevented CLAUDE.md §6's documented traps (dynamic_range is linear while
    #: state_separation directly above it is log2; gc_content is 0-100 while every
    #: neighbouring probability is 0-1).
    unit: str = ""


@dataclass(frozen=True, slots=True)
class HardFilter:
    """A disqualifying threshold. Failing one rejects the candidate before ranking."""

    metric: str
    minimum: float | None = None
    maximum: float | None = None
    reason: str = ""


@dataclass(frozen=True, slots=True)
class ScoringProfile:
    """A versioned, complete description of how candidates are compared.

    Recorded on every run, so a score stays interpretable after the profile changes.
    Metrics declare their own direction and range, which is what lets heterogeneous
    measurements be normalised onto one axis (design map 12).

    Attributes:
        name: Profile family, e.g. ``default``.
        version: Bumped whenever a change alters output.
        metrics: Every metric that counts, with its weight and normalization rule.
        hard_filters: Disqualifying thresholds, applied before ranking.
        tie_breakers: Metric names, in order, for candidates that score equally.
    """

    name: str
    version: str
    metrics: list[MetricSpec]
    hard_filters: list[HardFilter] = field(default_factory=list)
    tie_breakers: list[str] = field(default_factory=list)

    @property
    def label(self) -> str:
        """``default-v1``. What gets recorded on a run and shown in the report."""
        return f"{self.name}-{self.version}"

    def spec(self, metric_name: str) -> MetricSpec | None:
        """The declaration for one metric, or ``None`` if this profile ignores it.

        Returning ``None`` rather than raising is deliberate: a gate family emitting an
        extra metric the profile does not score must not break scoring.
        """
        for spec in self.metrics:
            if spec.name == metric_name:
                return spec
        return None

    def validate(self) -> None:
        """Fail loudly on an inconsistent profile rather than producing a silent bad score."""
        if not self.metrics:
            raise ScoringProfileError(f"Profile '{self.label}' declares no metrics.")

        names = [spec.name for spec in self.metrics]
        if len(names) != len(set(names)):
            raise ScoringProfileError(f"Profile '{self.label}' declares a metric twice.")

        total = sum(spec.weight for spec in self.metrics)
        if total <= 0:
            raise ScoringProfileError(f"Profile '{self.label}' has non-positive total weight.")

        for spec in self.metrics:
            low, high = spec.valid_range
            if low >= high:
                raise ScoringProfileError(
                    f"Metric '{spec.name}' in '{self.label}' has an empty valid_range."
                )
            if spec.direction not in (HIGHER_BETTER, LOWER_BETTER):
                raise ScoringProfileError(
                    f"Metric '{spec.name}' in '{self.label}' has an unknown direction."
                )

        for hard_filter in self.hard_filters:
            if self.spec(hard_filter.metric) is None:
                raise ScoringProfileError(
                    f"Hard filter in '{self.label}' references unknown metric "
                    f"'{hard_filter.metric}'."
                )


DEFAULT_V1 = ScoringProfile(
    name="default",
    # v2: state_separation, predicted_success_rate and circuit_complexity are now
    # computed rather than absent, and state_separation/orthogonality became SKIP
    # instead of TREAT_AS_WORST. Both move every stored score, so the label a run
    # records has to change with them.
    version="v2",
    metrics=[
        MetricSpec(
            name="state_separation",
            direction=HIGHER_BETTER,
            weight=3.0,
            valid_range=(0.0, 10.0),
            description="Differential expression between base and target state (log2 fold).",
            unit="log2 fold",
            # A property of the gene, from the DGE table. A `direct` submission pasted a
            # transcript and made no differential-expression comparison at all, so this
            # does not exist for one — SKIP rather than TREAT_AS_WORST, because scoring a
            # design 0.0 on the heaviest axis in the profile would penalise the *input
            # mode* rather than the design. The hard filter below is unaffected:
            # failed_filter already passes over a metric that was not reported.
            missing_behavior=SKIP,
        ),
        MetricSpec(
            name="trigger_accessibility",
            direction=HIGHER_BETTER,
            weight=2.0,
            valid_range=(0.0, 1.0),
            description="Predicted fraction of the trigger region free of self-structure.",
            unit="fraction 0-1",
        ),
        MetricSpec(
            name="gate_folding_energy",
            direction=LOWER_BETTER,
            weight=2.0,
            valid_range=(-60.0, 0.0),
            description="Predicted MFE of the gate in kcal/mol. More negative is more stable.",
            unit="kcal/mol",
        ),
        MetricSpec(
            name="predicted_leakage",
            direction=LOWER_BETTER,
            weight=2.5,
            valid_range=(0.0, 1.0),
            description="Proxy for OFF-state activation.",
            unit="fraction 0-1",
        ),
        MetricSpec(
            name="orthogonality",
            direction=HIGHER_BETTER,
            weight=1.5,
            valid_range=(0.0, 1.0),
            description="Predicted independence from other gates in the same circuit.",
            unit="fraction 0-1",
            # "In the same circuit" is the operative phrase, and no family computes this
            # because every circuit this build produces holds exactly one gate: there is
            # no other gate to be independent of, so the quantity does not exist yet
            # rather than being unmeasured. SKIP keeps an inapplicable metric out of both
            # halves of the weighted mean. When a real CircuitDesigner lands and circuits
            # hold several gates, this becomes measurable and the behaviour should go
            # back to TREAT_AS_WORST so a cross-reacting pair is actually punished.
            missing_behavior=SKIP,
        ),
        MetricSpec(
            name="gc_content",
            direction=HIGHER_BETTER,
            weight=0.5,
            valid_range=(30.0, 70.0),
            description="Percent GC of the assembled construct. Extremes hurt synthesis.",
            unit="percent 0-100",
        ),
        MetricSpec(
            name="dynamic_range",
            direction=HIGHER_BETTER,
            weight=2.0,
            valid_range=(1.0, 500.0),
            description="Predicted ON/OFF fold change.",
            unit="linear fold",
        ),
        MetricSpec(
            name="predicted_success_rate",
            direction=HIGHER_BETTER,
            weight=1.0,
            valid_range=(0.0, 1.0),
            description="Model confidence that the construct behaves as designed in vivo.",
            unit="fraction 0-1",
        ),
        MetricSpec(
            name="circuit_complexity",
            direction=LOWER_BETTER,
            weight=1.0,
            valid_range=(1.0, 10.0),
            description="Component count penalty. Simpler circuits are easier to build.",
            unit="component count",
        ),
    ],
    hard_filters=[
        HardFilter(
            metric="predicted_leakage",
            maximum=0.85,
            reason="Predicted OFF-state leakage above the acceptable threshold.",
        ),
        HardFilter(
            metric="state_separation",
            minimum=0.5,
            reason="Insufficient separation between base and target state.",
        ),
    ],
    tie_breakers=["state_separation", "predicted_leakage"],
)

PROFILES: dict[str, ScoringProfile] = {DEFAULT_V1.name: DEFAULT_V1}


def get_profile(name: str) -> ScoringProfile:
    """Look up a profile by name, validating it before returning."""
    try:
        profile = PROFILES[name]
    except KeyError:
        known = ", ".join(sorted(PROFILES)) or "none"
        raise ScoringProfileError(
            f"Unknown scoring profile '{name}'. Available profiles: {known}."
        ) from None
    profile.validate()
    return profile


def available_profiles() -> list[str]:
    """Profile names a submission may request. Surfaced at ``GET /api/version``."""
    return sorted(PROFILES)


# --- Custom scoring (docs/public-api.md §9.1) --------------------------------------
#
# A caller may re-weight the nine metrics and add hard filters through the public API.
# The API validates metric *names* against EngineCapabilities.metrics (engine.contract)
# and passes the block through unchanged as JobRequest.params["scoring"] — building the
# actual ScoringProfile happens only here, engine-side, per architecture.md §3.


def custom_scoring_label(
    base_name: str,
    weights: dict[str, float],
    hard_filters: list[dict],
    tie_breakers: list[str] | None,
) -> str:
    """``<hash8>`` — a pure function of the overrides, so two runs with identical
    weights get the same label and stay comparable (design map 12)."""
    canonical = {
        "base": base_name,
        "weights": dict(sorted(weights.items())),
        "hard_filters": sorted(
            (
                {
                    "metric": hf["metric"],
                    "minimum": hf.get("minimum"),
                    "maximum": hf.get("maximum"),
                }
                for hf in hard_filters
            ),
            key=lambda hf: hf["metric"],
        ),
        "tie_breakers": list(tie_breakers) if tie_breakers else [],
    }
    digest = hashlib.sha256(json.dumps(canonical, sort_keys=True).encode()).hexdigest()
    return digest[:8]


def derive_profile(
    base: ScoringProfile,
    *,
    weights: dict[str, float] | None = None,
    hard_filters: list[dict] | None = None,
    tie_breakers: list[str] | None = None,
) -> ScoringProfile:
    """A per-request variant of ``base``. Only ``weight`` on each metric may change —
    ``direction`` and ``valid_range`` are physics and units, not preference, so a caller
    who could widen ``valid_range`` could make their own numbers look better and quietly
    break comparability with every other run.

    ``weights`` merges by metric name: unlisted metrics keep ``base``'s weight. The
    clean way to say "ignore this metric" is ``weight=0.0``, not a deleted spec — the
    raw value stays measured and visible in the decomposition (CLAUDE.md §3's
    raw-values-only rule).

    ``hard_filters`` merges by metric name too, deliberately not a wholesale replace: a
    caller adding one new threshold (e.g. a ``dynamic_range`` floor) must not silently
    lose ``base``'s existing safety filters (``predicted_leakage``'s 0.85 ceiling,
    ``state_separation``'s 0.5 floor) just by specifying an unrelated one.

    ``tie_breakers`` replaces outright when given: order is the whole point of the
    field, so a partial list has no sensible merge.

    The result's ``label`` is ``custom-<hash8>`` (``custom_scoring_label``) — computable
    from the request alone, which is what lets the API echo it in ``resolved`` before
    the engine ever runs (``engine.client.label_for_custom_scoring``), without building
    a ``ScoringProfile`` itself.
    """
    weights = weights or {}
    hard_filter_overrides = hard_filters or []
    resolved_tie_breakers = list(tie_breakers) if tie_breakers else list(base.tie_breakers)

    new_metrics = [
        replace(spec, weight=weights[spec.name]) if spec.name in weights else spec
        for spec in base.metrics
    ]

    merged_filters = {hf.metric: hf for hf in base.hard_filters}
    for override in hard_filter_overrides:
        merged_filters[override["metric"]] = HardFilter(
            metric=override["metric"],
            minimum=override.get("minimum"),
            maximum=override.get("maximum"),
            reason=override.get("reason", ""),
        )

    label = custom_scoring_label(base.name, weights, hard_filter_overrides, tie_breakers)

    profile = ScoringProfile(
        name="custom",
        version=label,
        metrics=new_metrics,
        hard_filters=list(merged_filters.values()),
        tie_breakers=resolved_tie_breakers,
    )
    profile.validate()
    return profile


def resolve_profile(base_name: str, overrides: dict | None = None) -> ScoringProfile:
    """What the real pipeline actually calls: ``base_name`` is
    ``AnalysisRun.scoring_profile`` (always a known name — kept that way so
    ``_validate_against_capabilities`` keeps working unmodified), ``overrides`` is
    ``JobRequest.params.get("scoring")``. No overrides, or an empty ``weights`` /
    ``hard_filters`` / ``tie_breakers``, returns ``base`` unchanged — most runs never
    pay for a hash.
    """
    base = get_profile(base_name)
    if not overrides:
        return base

    weights = overrides.get("weights") or {}
    hard_filters = overrides.get("hard_filters") or []
    tie_breakers = overrides.get("tie_breakers") or []
    if not (weights or hard_filters or tie_breakers):
        return base

    return derive_profile(
        base, weights=weights, hard_filters=hard_filters, tie_breakers=tie_breakers
    )
