"""从真实风险规则运行与人工处置构建分阶段发布质量指标。"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any, Literal

from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session

from app.models.agent_asset import AgentAsset
from app.models.agent_asset_release_telemetry import (
    AgentAssetReleaseAuditSample,
    AgentAssetReleaseLabel,
    AgentAssetReleaseObservation,
)
from app.models.risk_disposition import RiskDispositionEvent
from app.models.risk_observation import RiskObservation
from app.services.agent_asset_release_guard import ReleaseEvaluationInput
from app.services.agent_asset_release_sampling import AgentAssetReleaseSamplingService
from app.services.agent_asset_release_telemetry_crypto import (
    deterministic_fingerprint as _fingerprint,
)
from app.services.agent_asset_release_telemetry_crypto import (
    json_fingerprint as _json_fingerprint,
)
from app.services.agent_asset_release_telemetry_crypto import (
    release_pseudonym_fingerprint,
    release_source_fingerprint,
    release_source_fingerprints,
)
from app.services.agent_asset_release_telemetry_crypto import (
    stable_uuid as _stable_uuid,
)
from app.services.agent_asset_release_telemetry_values import (
    release_stage as _stage,
)
from app.services.agent_asset_release_telemetry_values import (
    required_value as _required,
)
from app.services.agent_asset_release_telemetry_values import (
    safe_code as _safe_code,
)
from app.services.agent_asset_release_telemetry_values import (
    strict_bool as _strict_bool,
)

ReleaseTelemetryStage = Literal["shadow", "canary", "active"]
ReleaseTelemetryLabelValue = Literal[
    "confirmed",
    "false_positive",
    "risk_present",
    "risk_absent",
]

_BUSINESS_STAGES = {"expense_application", "reimbursement"}
_FAILURE_CODES = {
    "none",
    "evaluator_error",
    "artifact_integrity_error",
    "unsupported_evaluator",
    "timeout",
}


class ReleaseTelemetryError(RuntimeError):
    """发布遥测输入不可信或与当前发布状态冲突。"""


class ReleaseTelemetryIdempotencyConflict(ReleaseTelemetryError):
    """幂等键已被不同事实使用。"""


class ReleaseTelemetryStaleRelease(ReleaseTelemetryError):
    """运行观察不再属于资产当前的 release/stage/version。"""


class ReleaseTelemetryCollecting(ReleaseTelemetryError):
    """真实标签证据尚未满足发布评测输入要求。"""


@dataclass(frozen=True, slots=True)
class ReleaseObservationInput:
    tenant_id: str
    asset_id: str
    release_id: str
    stage: ReleaseTelemetryStage
    version: str
    rule_code: str
    source_key: str
    candidate_hit: bool
    baseline_hit: bool | None = None
    runtime_status: Literal["completed", "failed"] = "completed"
    failure_code: str = "none"
    business_stage: str = "reimbursement"


@dataclass(frozen=True, slots=True)
class ReleaseTelemetryAggregate:
    tenant_id: str
    asset_id: str
    release_id: str
    stage: str
    version: str
    status: Literal["collecting", "ready"]
    reasons: tuple[str, ...]
    observed_count: int
    completed_count: int
    runtime_failure_count: int
    candidate_hit_count: int
    candidate_labeled_count: int
    candidate_pending_label_count: int
    candidate_confirmed_count: int
    candidate_false_positive_count: int
    precision: float | None
    baseline_hit_count: int
    baseline_labeled_count: int
    baseline_pending_label_count: int
    baseline_confirmed_count: int
    baseline_false_positive_count: int
    baseline_precision: float | None
    false_negative_count: int | None = None
    estimated_false_negative_count: float | None = None
    false_negative_upper_bound: float | None = None
    negative_sample_count: int = 0
    negative_labeled_count: int = 0
    negative_pending_label_count: int = 0
    random_negative_population_count: int = 0
    random_negative_sample_count: int = 0
    random_negative_labeled_count: int = 0
    random_negative_false_negative_count: int = 0
    recall: float | None = None
    recall_lower_bound: float | None = None
    recall_confidence_level: float = 0.95
    recall_method: str = "unavailable"
    negative_ground_truth_status: str = "unavailable"

    def to_release_evaluation_input(self) -> ReleaseEvaluationInput:
        """只在所有候选正例已有可信标签时交给 Release Guard。"""

        if self.status != "ready":
            raise ReleaseTelemetryCollecting(
                "发布遥测仍在采集真实标签，不能把未标注样本当作成功。"
            )
        guarded_precision = (
            self.precision if self.candidate_pending_label_count == 0 else None
        )
        if guarded_precision is None and self.runtime_failure_count == 0:
            raise ReleaseTelemetryCollecting(
                "发布遥测缺少完整可信标签，不能把部分精度当作成功。"
            )
        return ReleaseEvaluationInput(
            total=self.observed_count,
            failure_count=self.runtime_failure_count,
            precision=guarded_precision,
            baseline_precision=self.baseline_precision,
            details={
                "metric_source": "release_runtime_telemetry",
                "release_id": self.release_id,
                "stage": self.stage,
                "version": self.version,
                "completed_count": self.completed_count,
                "candidate_hit_count": self.candidate_hit_count,
                "candidate_labeled_count": self.candidate_labeled_count,
                "candidate_pending_label_count": self.candidate_pending_label_count,
                "baseline_hit_count": self.baseline_hit_count,
                "baseline_labeled_count": self.baseline_labeled_count,
                "baseline_precision_status": (
                    "available" if self.baseline_precision is not None else "unavailable"
                ),
                "false_negative_count": self.false_negative_count,
                "estimated_false_negative_count": self.estimated_false_negative_count,
                "false_negative_upper_bound": self.false_negative_upper_bound,
                "negative_sample_count": self.negative_sample_count,
                "negative_labeled_count": self.negative_labeled_count,
                "negative_pending_label_count": self.negative_pending_label_count,
                "random_negative_population_count": self.random_negative_population_count,
                "random_negative_sample_count": self.random_negative_sample_count,
                "random_negative_labeled_count": self.random_negative_labeled_count,
                "recall": self.recall,
                "recall_lower_bound": self.recall_lower_bound,
                "recall_confidence_level": self.recall_confidence_level,
                "recall_method": self.recall_method,
                "negative_ground_truth_status": self.negative_ground_truth_status,
            },
        )


class AgentAssetReleaseTelemetryService:
    """生产真实运行样本，接收可信人工结论并生成保守发布指标。"""

    def __init__(self, db: Session) -> None:
        self.db = db

    def record_observation(
        self,
        payload: ReleaseObservationInput,
    ) -> AgentAssetReleaseObservation:
        tenant_id = _required(payload.tenant_id, "tenant_id", 64)
        asset_id = _required(payload.asset_id, "asset_id", 36)
        release_id = _safe_code(payload.release_id, "release_id", 64)
        stage = _stage(payload.stage)
        version = _safe_code(payload.version, "version", 30)
        rule_code = _safe_code(payload.rule_code, "rule_code", 100)
        source_key = _required(payload.source_key, "source_key", 500)
        business_stage = str(payload.business_stage or "").strip().lower()
        if business_stage not in _BUSINESS_STAGES:
            raise ValueError("business_stage must be expense_application or reimbursement.")
        runtime_status = str(payload.runtime_status or "").strip().lower()
        if runtime_status not in {"completed", "failed"}:
            raise ValueError("runtime_status must be completed or failed.")
        failure_code = str(payload.failure_code or "none").strip().lower()
        if failure_code not in _FAILURE_CODES:
            raise ValueError("failure_code is not an approved structured code.")
        if runtime_status == "completed" and failure_code != "none":
            raise ValueError("completed observation cannot contain a failure code.")
        if runtime_status == "failed" and failure_code == "none":
            raise ValueError("failed observation requires a structured failure code.")
        candidate_hit = _strict_bool(payload.candidate_hit, "candidate_hit")
        baseline_hit = (
            None
            if payload.baseline_hit is None
            else _strict_bool(payload.baseline_hit, "baseline_hit")
        )

        _asset, release_state = self._require_current_release(
            tenant_id=tenant_id,
            asset_id=asset_id,
            release_id=release_id,
            stage=stage,
            version=version,
            rule_code=rule_code,
        )
        source_fingerprint = release_source_fingerprint(
            tenant_id=tenant_id,
            source_key=source_key,
            rule_code=rule_code,
        )
        identity = {
            "tenant_id": tenant_id,
            "asset_id": asset_id,
            "release_id": release_id,
            "stage": stage,
            "version": version,
            "rule_code": rule_code,
            "business_stage": business_stage,
            "source_fingerprint": source_fingerprint,
            "candidate_hit": candidate_hit,
            "baseline_hit": baseline_hit,
            "runtime_status": runtime_status,
            "failure_code": failure_code,
        }
        payload_fingerprint = _json_fingerprint(identity)
        observation_key_hash = _fingerprint(
            "observation",
            tenant_id,
            asset_id,
            release_id,
            stage,
            version,
            rule_code,
            business_stage,
            source_fingerprint,
        )
        idempotency_key = f"aro:{observation_key_hash}"
        replay = self._observation_replay(tenant_id, idempotency_key, payload_fingerprint)
        if replay is not None:
            with self.db.begin_nested():
                AgentAssetReleaseSamplingService(self.db).ensure_sample(
                    observation=replay,
                    source_reference=source_key,
                    release_state=release_state,
                )
            return replay

        item = AgentAssetReleaseObservation(
            id=_stable_uuid(idempotency_key),
            **identity,
            source_kind="expense_claim_risk",
            idempotency_key=idempotency_key,
            payload_fingerprint=payload_fingerprint,
            created_at=datetime.now(UTC),
        )
        try:
            with self.db.begin_nested():
                self.db.add(item)
                self.db.flush()
                AgentAssetReleaseSamplingService(self.db).ensure_sample(
                    observation=item,
                    source_reference=source_key,
                    release_state=release_state,
                )
        except IntegrityError:
            replay = self._observation_replay(
                tenant_id,
                idempotency_key,
                payload_fingerprint,
            )
            if replay is None:
                raise
            with self.db.begin_nested():
                AgentAssetReleaseSamplingService(self.db).ensure_sample(
                    observation=replay,
                    source_reference=source_key,
                    release_state=release_state,
                )
            return replay
        return item

    def record_expense_risk_result(
        self,
        *,
        tenant_id: str,
        claim_id: str,
        result: dict[str, Any],
        business_stage: str = "reimbursement",
    ) -> list[AgentAssetReleaseObservation]:
        """把现有 evaluate_platform_risk_rules 返回值转换成真实遥测样本。"""

        normalized_tenant = _required(tenant_id, "tenant_id", 64)
        normalized_claim = _required(claim_id, "claim_id", 100)
        flags = [item for item in result.get("flags", []) if isinstance(item, dict)]
        recorded: list[AgentAssetReleaseObservation] = []
        for raw in result.get("shadow_evaluations", []):
            if not isinstance(raw, dict):
                raise ValueError("shadow_evaluations must contain structured objects.")
            if str(raw.get("release_stage") or "").strip().lower() != "shadow":
                raise ValueError("shadow_evaluations contains a non-shadow release sample.")
            candidate_hit = _strict_bool(raw.get("hit"), "hit")
            asset_id = _required(raw.get("asset_id"), "asset_id", 36)
            rule_code = _safe_code(raw.get("rule_code"), "rule_code", 100)
            version = _safe_code(raw.get("rule_version"), "rule_version", 30)
            state = self._release_state_for_asset(normalized_tenant, asset_id)
            baseline_version = str(state.get("previous_version") or "").strip()
            baseline_hit = any(
                str(flag.get("rule_code") or "").strip() == rule_code
                and str(flag.get("rule_version") or "").strip() == baseline_version
                and str(flag.get("release_mode") or "enforced").strip() == "enforced"
                for flag in flags
            )
            recorded.append(
                self.record_observation(
                    ReleaseObservationInput(
                        tenant_id=normalized_tenant,
                        asset_id=asset_id,
                        release_id=_required(state.get("release_id"), "release_id", 64),
                        stage="shadow",
                        version=version,
                        rule_code=rule_code,
                        source_key=normalized_claim,
                        candidate_hit=candidate_hit,
                        baseline_hit=baseline_hit,
                        business_stage=business_stage,
                    )
                )
            )

        for flag in flags:
            stage = str(flag.get("release_stage") or "").strip().lower()
            if stage not in {"canary", "active"}:
                continue
            rule_code = _safe_code(flag.get("rule_code"), "rule_code", 100)
            asset = self._asset_for_rule_code(normalized_tenant, rule_code)
            state = self._release_state(asset)
            version = _safe_code(flag.get("rule_version"), "rule_version", 30)
            recorded.append(
                self.record_observation(
                    ReleaseObservationInput(
                        tenant_id=normalized_tenant,
                        asset_id=asset.id,
                        release_id=_required(state.get("release_id"), "release_id", 64),
                        stage=stage,  # type: ignore[arg-type]
                        version=version,
                        rule_code=rule_code,
                        source_key=normalized_claim,
                        candidate_hit=True,
                        baseline_hit=None,
                        business_stage=business_stage,
                    )
                )
            )
        return recorded

    def record_manifest_evaluation(
        self,
        *,
        tenant_id: str,
        claim_id: str,
        manifest: dict[str, Any],
        hit: bool,
        baseline_hit: bool | None = None,
        runtime_status: Literal["completed", "failed"] = "completed",
        failure_code: str = "none",
        business_stage: str = "reimbursement",
    ) -> AgentAssetReleaseObservation:
        """在规则执行循环内记录候选命中或未命中，覆盖 Canary 的负样本。"""

        normalized_tenant = _required(tenant_id, "tenant_id", 64)
        asset_id = _required(manifest.get("_rule_asset_id"), "asset_id", 36)
        stage = _stage(manifest.get("_release_stage"))
        mode = str(manifest.get("_release_mode") or "").strip().lower()
        if (stage == "shadow" and mode != "shadow") or (
            stage in {"canary", "active"} and mode != "enforced"
        ):
            raise ValueError("Only the candidate route can emit release telemetry.")
        version = _safe_code(manifest.get("_rule_version"), "rule_version", 30)
        rule_code = _safe_code(manifest.get("rule_code"), "rule_code", 100)
        state = self._release_state_for_asset(normalized_tenant, asset_id)
        return self.record_observation(
            ReleaseObservationInput(
                tenant_id=normalized_tenant,
                asset_id=asset_id,
                release_id=_required(state.get("release_id"), "release_id", 64),
                stage=stage,  # type: ignore[arg-type]
                version=version,
                rule_code=rule_code,
                source_key=_required(claim_id, "claim_id", 100),
                candidate_hit=_strict_bool(hit, "hit") if runtime_status == "completed" else False,
                baseline_hit=baseline_hit,
                runtime_status=runtime_status,
                failure_code=failure_code,
                business_stage=business_stage,
            )
        )

    def record_review_label(
        self,
        *,
        tenant_id: str,
        observation_id: str,
        label: Literal["confirmed", "false_positive"],
        request_id: str,
        actor_id: str,
    ) -> AgentAssetReleaseLabel:
        """记录专用发布复核队列给出的类型化结论，不接收评论或业务正文。"""

        return self._record_label(
            tenant_id=tenant_id,
            observation_id=observation_id,
            label=label,
            verification_source="release_review",
            source_event_key=_required(request_id, "request_id", 160),
            actor_key=_required(actor_id, "actor_id", 160),
        )

    def record_blind_review_label(
        self,
        *,
        tenant_id: str,
        observation_id: str,
        ground_truth: Literal["risk_present", "risk_absent"],
        request_id: str,
        actor_id: str,
    ) -> AgentAssetReleaseLabel:
        """记录不披露候选结论的独立业务真值。"""

        return self._record_label(
            tenant_id=tenant_id,
            observation_id=observation_id,
            label=ground_truth,
            verification_source="blind_release_review",
            source_event_key=_required(request_id, "request_id", 160),
            actor_key=_required(actor_id, "actor_id", 160),
        )

    def record_risk_disposition_label(
        self,
        *,
        tenant_id: str,
        observation_id: str,
        disposition_event_id: str,
    ) -> AgentAssetReleaseLabel:
        """只接受数据库中真实存在的 confirm/false_positive 处置事件。"""

        normalized_tenant = _required(tenant_id, "tenant_id", 64)
        telemetry = self._observation(normalized_tenant, observation_id)
        event = self.db.scalar(
            select(RiskDispositionEvent).where(
                RiskDispositionEvent.id == disposition_event_id,
                RiskDispositionEvent.tenant_id == normalized_tenant,
            )
        )
        if event is None:
            raise LookupError("Risk disposition event not found.")
        if event.action not in {"confirm", "false_positive"}:
            raise ValueError("Only typed confirm/false_positive events can label release samples.")
        risk_observation = self.db.scalar(
            select(RiskObservation).where(
                RiskObservation.id == event.observation_id,
                RiskObservation.tenant_id == normalized_tenant,
            )
        )
        if risk_observation is None:
            raise LookupError("Risk observation not found.")
        rule_code = str((risk_observation.decision_trace_json or {}).get("rule_code") or "").strip()
        if not rule_code and risk_observation.policy_refs_json:
            rule_code = str(risk_observation.policy_refs_json[0] or "").strip()
        expected_sources = release_source_fingerprints(
            tenant_id=normalized_tenant,
            source_key=_required(risk_observation.claim_id, "claim_id", 100),
            rule_code=rule_code,
        )
        if rule_code != telemetry.rule_code or telemetry.source_fingerprint not in expected_sources:
            raise PermissionError("Risk disposition does not belong to this release observation.")
        state = self._release_state_for_asset(normalized_tenant, telemetry.asset_id)
        trusted_versions = {
            telemetry.version,
            str(state.get("previous_version") or "").strip(),
        }
        if str(risk_observation.algorithm_version or "").strip() not in trusted_versions:
            raise PermissionError("Risk disposition version does not match the release sample.")
        return self._record_label(
            tenant_id=normalized_tenant,
            observation_id=telemetry.id,
            label="confirmed" if event.action == "confirm" else "false_positive",
            verification_source="typed_risk_disposition",
            source_event_key=event.id,
            actor_key=event.actor_id,
        )

    def aggregate(
        self,
        *,
        tenant_id: str,
        asset_id: str,
        release_id: str,
        stage: ReleaseTelemetryStage,
        version: str,
    ) -> ReleaseTelemetryAggregate:
        from app.services.agent_asset_release_aggregation import (
            build_release_telemetry_aggregate,
        )

        normalized_tenant = _required(tenant_id, "tenant_id", 64)
        normalized_asset = _required(asset_id, "asset_id", 36)
        normalized_release = _safe_code(release_id, "release_id", 64)
        normalized_stage = _stage(stage)
        normalized_version = _safe_code(version, "version", 30)
        _asset, release_state = self._require_current_release(
            tenant_id=normalized_tenant,
            asset_id=normalized_asset,
            release_id=normalized_release,
            stage=normalized_stage,
            version=normalized_version,
        )
        return build_release_telemetry_aggregate(
            db=self.db,
            tenant_id=normalized_tenant,
            asset_id=normalized_asset,
            release_id=normalized_release,
            stage=normalized_stage,
            version=normalized_version,
            release_state=release_state,
        )

    def _record_label(
        self,
        *,
        tenant_id: str,
        observation_id: str,
        label: str,
        verification_source: str,
        source_event_key: str,
        actor_key: str,
    ) -> AgentAssetReleaseLabel:
        normalized_tenant = _required(tenant_id, "tenant_id", 64)
        normalized_label = str(label or "").strip().lower()
        if normalized_label not in {
            "confirmed",
            "false_positive",
            "risk_present",
            "risk_absent",
        }:
            raise ValueError("label is not an approved typed release ground truth.")
        if verification_source == "blind_release_review":
            if normalized_label not in {"risk_present", "risk_absent"}:
                raise ValueError(
                    "Blind release review requires risk_present or risk_absent."
                )
        elif normalized_label not in {"confirmed", "false_positive"}:
            raise ValueError(
                "Typed dispositions and release reviews require confirmed or "
                "false_positive."
            )
        observation = self._observation(normalized_tenant, observation_id)
        self._require_current_release(
            tenant_id=normalized_tenant,
            asset_id=observation.asset_id,
            release_id=observation.release_id,
            stage=observation.stage,
            version=observation.version,
            rule_code=observation.rule_code,
            lock=True,
        )
        sample = self.db.scalar(
            select(AgentAssetReleaseAuditSample).where(
                AgentAssetReleaseAuditSample.tenant_id == normalized_tenant,
                AgentAssetReleaseAuditSample.observation_id == observation.id,
            )
        )
        if verification_source == "blind_release_review" and sample is None:
            raise ValueError("Blind review requires a selected release audit sample.")
        if not observation.candidate_hit and observation.baseline_hit is not True:
            if verification_source != "blind_release_review":
                raise ValueError(
                    "Negative executions require independent ground truth from a selected "
                    "blind-review sample."
                )
        source_event_fingerprint = release_pseudonym_fingerprint(
            "label-source",
            normalized_tenant,
            source_event_key,
        )
        actor_fingerprint = release_pseudonym_fingerprint(
            "label-actor",
            normalized_tenant,
            actor_key,
        )
        identity = {
            "tenant_id": normalized_tenant,
            "observation_id": observation.id,
            "asset_id": observation.asset_id,
            "release_id": observation.release_id,
            "stage": observation.stage,
            "version": observation.version,
            "label": normalized_label,
            "verification_source": verification_source,
            "source_event_fingerprint": source_event_fingerprint,
            "actor_fingerprint": actor_fingerprint,
        }
        payload_fingerprint = _json_fingerprint(identity)
        label_key_hash = _fingerprint(
            "label",
            normalized_tenant,
            observation.id,
            source_event_fingerprint,
        )
        idempotency_key = f"arl:{label_key_hash}"
        replay = self._label_replay(normalized_tenant, idempotency_key, payload_fingerprint)
        if replay is not None:
            return replay
        item = AgentAssetReleaseLabel(
            id=_stable_uuid(idempotency_key),
            **identity,
            idempotency_key=idempotency_key,
            payload_fingerprint=payload_fingerprint,
            created_at=datetime.now(UTC),
        )
        try:
            with self.db.begin_nested():
                self.db.add(item)
                self.db.flush()
        except IntegrityError:
            replay = self._label_replay(
                normalized_tenant,
                idempotency_key,
                payload_fingerprint,
            )
            if replay is None:
                raise
            return replay
        return item

    def _observation(self, tenant_id: str, observation_id: str) -> AgentAssetReleaseObservation:
        item = self.db.scalar(
            select(AgentAssetReleaseObservation).where(
                AgentAssetReleaseObservation.tenant_id == tenant_id,
                AgentAssetReleaseObservation.id == observation_id,
            )
        )
        if item is None:
            raise LookupError("Release observation not found.")
        return item

    def _observation_replay(
        self,
        tenant_id: str,
        idempotency_key: str,
        payload_fingerprint: str,
    ) -> AgentAssetReleaseObservation | None:
        item = self.db.scalar(
            select(AgentAssetReleaseObservation).where(
                AgentAssetReleaseObservation.tenant_id == tenant_id,
                AgentAssetReleaseObservation.idempotency_key == idempotency_key,
            )
        )
        if item is not None and item.payload_fingerprint != payload_fingerprint:
            raise ReleaseTelemetryIdempotencyConflict(
                "Observation idempotency key was reused with different facts."
            )
        return item

    def _label_replay(
        self,
        tenant_id: str,
        idempotency_key: str,
        payload_fingerprint: str,
    ) -> AgentAssetReleaseLabel | None:
        item = self.db.scalar(
            select(AgentAssetReleaseLabel).where(
                AgentAssetReleaseLabel.tenant_id == tenant_id,
                AgentAssetReleaseLabel.idempotency_key == idempotency_key,
            )
        )
        if item is not None and item.payload_fingerprint != payload_fingerprint:
            raise ReleaseTelemetryIdempotencyConflict(
                "Label idempotency key was reused with different facts."
            )
        return item

    def _require_current_release(
        self,
        *,
        tenant_id: str,
        asset_id: str,
        release_id: str,
        stage: str,
        version: str,
        rule_code: str | None = None,
        lock: bool = False,
    ) -> tuple[AgentAsset, dict[str, Any]]:
        statement = select(AgentAsset).where(
            AgentAsset.id == asset_id,
            (
                ((AgentAsset.scope == "tenant") & (AgentAsset.tenant_id == tenant_id))
                | ((AgentAsset.scope == "platform") & (AgentAsset.tenant_id == "platform"))
            ),
        )
        bind = self.db.get_bind()
        if lock and bind is not None and bind.dialect.name == "postgresql":
            statement = statement.with_for_update().execution_options(populate_existing=True)
        asset = self.db.scalar(statement)
        if asset is None:
            raise LookupError("Agent asset not found.")
        configured_tenant = str((asset.config_json or {}).get("tenant_id") or "").strip()
        if asset.scope == "tenant" and configured_tenant not in {"", tenant_id}:
            raise LookupError("Agent asset not found.")
        if asset.scope == "platform" and configured_tenant != tenant_id:
            raise LookupError("Agent asset not found.")
        if rule_code is not None and str(asset.code or "").strip() != rule_code:
            raise ReleaseTelemetryStaleRelease("Rule code no longer matches the release asset.")
        state = self._release_state(asset)
        if (
            str(state.get("release_id") or "").strip() != release_id
            or str(state.get("stage") or "").strip() != stage
            or str(state.get("candidate_version") or "").strip() != version
        ):
            raise ReleaseTelemetryStaleRelease(
                "Observation or label targets a stale release/stage/version."
            )
        return asset, state

    def _release_state_for_asset(self, tenant_id: str, asset_id: str) -> dict[str, Any]:
        asset = self.db.scalar(
            select(AgentAsset).where(
                AgentAsset.id == asset_id,
                (
                    ((AgentAsset.scope == "tenant") & (AgentAsset.tenant_id == tenant_id))
                    | ((AgentAsset.scope == "platform") & (AgentAsset.tenant_id == "platform"))
                ),
            )
        )
        if asset is None:
            raise LookupError("Agent asset not found.")
        configured_tenant = str((asset.config_json or {}).get("tenant_id") or "").strip()
        if asset.scope == "tenant" and configured_tenant not in {"", tenant_id}:
            raise LookupError("Agent asset not found.")
        if asset.scope == "platform" and configured_tenant != tenant_id:
            raise LookupError("Agent asset not found.")
        return self._release_state(asset)

    def _asset_for_rule_code(self, tenant_id: str, rule_code: str) -> AgentAsset:
        asset = self.db.scalar(
            select(AgentAsset)
            .where(
                AgentAsset.code == rule_code,
                (
                    ((AgentAsset.scope == "tenant") & (AgentAsset.tenant_id == tenant_id))
                    | ((AgentAsset.scope == "platform") & (AgentAsset.tenant_id == "platform"))
                ),
            )
            .order_by(AgentAsset.scope.desc())
        )
        if asset is None:
            raise LookupError("Agent asset not found.")
        configured_tenant = str((asset.config_json or {}).get("tenant_id") or "").strip()
        if asset.scope == "tenant" and configured_tenant not in {"", tenant_id}:
            raise LookupError("Agent asset not found.")
        if asset.scope == "platform" and configured_tenant != tenant_id:
            raise LookupError("Agent asset not found.")
        return asset

    @staticmethod
    def _release_state(asset: AgentAsset) -> dict[str, Any]:
        config = asset.config_json if isinstance(asset.config_json, dict) else {}
        state = config.get("release_guard")
        return dict(state) if isinstance(state, dict) else {}
