"""判定 find_agent 调度执行是否真正成功完成。"""
from __future__ import annotations

from dataclasses import dataclass

from supply_agent.types import AgentResult
from supply_infra.services.video_discovery_service import get_video_discovery_service


@dataclass(frozen=True)
class FindAgentRunOutcome:
    """一次运行的技术完成状态与独立业务结果。"""

    succeeded: bool
    business_outcome: str
    goal_met: bool
    valid_primary_count: int
    failure_reason: str | None = None


def evaluate_find_agent_run(
    run_id: str,
    agent_result: AgentResult | None = None,
) -> FindAgentRunOutcome:
    """技术完成与业务达标分开判定；业务不足 5 条不会触发重跑。"""
    del agent_result
    run = get_video_discovery_service().lookup_run(run_id)
    if run is None:
        return FindAgentRunOutcome(
            succeeded=False,
            business_outcome="failed",
            goal_met=False,
            valid_primary_count=0,
            failure_reason="run_not_found",
        )

    status = str(run.get("status") or "")
    valid_primary_count = int(run.get("valid_primary_count") or 0)
    business_outcome = str(run.get("outcome_status") or "")
    if status == "finished" and business_outcome in {
        "goal_met",
        "partial",
        "no_match",
    }:
        return FindAgentRunOutcome(
            succeeded=True,
            business_outcome=business_outcome,
            goal_met=business_outcome == "goal_met",
            valid_primary_count=valid_primary_count,
        )

    failure_reason = "run_failed" if status == "failed" else "run_not_finished"
    return FindAgentRunOutcome(
        succeeded=False,
        business_outcome="failed",
        goal_met=False,
        valid_primary_count=valid_primary_count,
        failure_reason=failure_reason,
    )
