from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.agent_run import AgentRun
from app.services.knowledge_tenant_scope import require_knowledge_tenant_id


def resolve_trusted_knowledge_run_tenant(db: Session, agent_run_id: str) -> str:
    """只从持久化 Agent Run 还原后台知识任务的可信租户。"""
    run = db.scalar(select(AgentRun).where(AgentRun.run_id == agent_run_id))
    if run is None:
        raise LookupError("知识索引任务关联的 Agent Run 不存在。")
    route_tenant_id = require_knowledge_tenant_id(
        (run.route_json or {}).get("tenant_id")
    )
    ontology_tenant_id = require_knowledge_tenant_id(
        (run.ontology_json or {}).get("tenant_id")
    )
    if route_tenant_id != ontology_tenant_id:
        raise ValueError("知识索引任务的 Agent Run 租户上下文冲突。")
    return route_tenant_id
