"""风险人工结论提交后的发布标签与门禁同步。"""

from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.logging import get_logger
from app.models.agent_asset import AgentAsset
from app.services.agent_asset_release_disposition_labels import (
    AgentAssetReleaseDispositionLabelService,
)
from app.services.agent_asset_release_monitor import AgentAssetReleaseMonitor

logger = get_logger("app.services.risk_disposition_release_sync")


def sync_risk_disposition_release(
    db: Session,
    *,
    tenant_id: str,
    disposition_event_id: str,
) -> None:
    """追加可信标签并用最新真实样本触发租户级发布门禁。"""

    try:
        labels = AgentAssetReleaseDispositionLabelService(db).record_current_labels(
            tenant_id=tenant_id,
            disposition_event_id=disposition_event_id,
        )
        if not labels:
            return
        db.commit()
    except Exception:
        db.rollback()
        # 发布学习链路故障不能撤销已成功的人工风险处置。
        logger.exception(
            "release telemetry labeling failed for disposition_event_id=%s",
            disposition_event_id,
        )
        return

    for asset_id in sorted({label.asset_id for label in labels}):
        asset = db.scalar(
            select(AgentAsset).where(
                AgentAsset.id == asset_id,
                AgentAsset.scope == "tenant",
                AgentAsset.tenant_id == tenant_id,
            )
        )
        config = (
            asset.config_json
            if asset is not None and isinstance(asset.config_json, dict)
            else {}
        )
        # 全局资产的门禁必须由平台聚合任务处理，不能由单租户样本单独回滚。
        if (
            asset is None
            or asset.scope != "tenant"
            or asset.tenant_id != tenant_id
            or str(config.get("tenant_id") or "").strip() not in {"", tenant_id}
        ):
            continue
        try:
            AgentAssetReleaseMonitor(db).evaluate_current(
                tenant_id=tenant_id,
                asset_id=asset_id,
                actor="release-telemetry-monitor",
            )
        except Exception:
            db.rollback()
            # 真实标签已经提交，周期任务可据此安全重试门禁评测。
            logger.exception(
                "release monitor failed after disposition_event_id=%s asset_id=%s",
                disposition_event_id,
                asset_id,
            )
