from __future__ import annotations

from app.models.agent_asset import AgentAsset
from app.services.agent_asset_release_guard import AgentAssetReleaseGuardService


class AgentAssetRiskRulePublishMixin:
    """把既有“发布”动作收口为强制受控的 shadow 发布入口。"""

    def publish_risk_rule(
        self,
        asset_id: str,
        *,
        actor: str,
        tenant_id: str | None = None,
        allow_global_management: bool = False,
        request_id: str | None = None,
    ) -> AgentAsset:
        asset = self._resolve_asset(asset_id)
        self._require_json_risk_asset(asset)
        version = self._resolve_target_version(asset, None)
        config = asset.config_json if isinstance(asset.config_json, dict) else {}
        revision = config.get("revision_draft")
        if isinstance(revision, dict) and str(revision.get("version") or "").strip() == version:
            if revision.get("generation_status") != "completed":
                raise ValueError("修订版本尚未重新生成，不能进入影子发布。")

        AgentAssetReleaseGuardService(
            self.db,
            rule_library_manager=self.rule_library_manager,
        ).start_shadow(
            asset.id,
            version,
            actor=actor,
            tenant_id=(
                str(tenant_id or "").strip() or str(config.get("tenant_id") or "").strip() or None
            ),
            allow_global_management=allow_global_management,
            request_id=request_id,
        )
        refreshed = self.repository.get(asset.id)
        if refreshed is None:
            raise LookupError("Asset not found")
        return refreshed
