"""Public run creation and sync/async entry points."""

from __future__ import annotations

import asyncio

from find_agent_v2.agent import FindAgentV2, create_find_agent_v2
from find_agent_v2.service import get_find_agent_v2_service
from find_agent_v2.state import FindAgentResult
from supply_agent.config import Settings


def create_find_agent_v2_run(
    *,
    user_input: str,
    demand_word: str,
    demand_grade_id: int | None = None,
    run_id: str | None = None,
    rule_config: dict | None = None,
) -> str:
    """Create a run in the new table namespace; old run IDs are never reused implicitly."""
    return get_find_agent_v2_service().create_run(
        user_input=user_input,
        demand_word=demand_word,
        demand_grade_id=demand_grade_id,
        run_id=run_id,
        rule_config=rule_config,
    )


async def arun_find_agent_v2(
    user_input: str,
    *,
    run_id: str,
    agent: FindAgentV2 | None = None,
    settings: Settings | None = None,
    model: str | None = None,
    resume: bool = False,
) -> FindAgentResult:
    runner = agent or create_find_agent_v2(settings=settings, model=model)
    return await runner.arun(run_id=run_id, user_input=user_input, resume=resume)


def run_find_agent_v2(
    user_input: str,
    *,
    run_id: str,
    agent: FindAgentV2 | None = None,
    settings: Settings | None = None,
    model: str | None = None,
    resume: bool = False,
) -> FindAgentResult:
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(arun_find_agent_v2(
            user_input,
            run_id=run_id,
            agent=agent,
            settings=settings,
            model=model,
            resume=resume,
        ))
    raise RuntimeError("run_find_agent_v2 不能在已运行的事件循环内调用；请使用 arun_find_agent_v2")


def run_prepared_find_agent_v2(
    run_id: str,
    *,
    agent: FindAgentV2 | None = None,
    settings: Settings | None = None,
    model: str | None = None,
    resume: bool = False,
) -> FindAgentResult:
    """Execute a prepared run using its database-persisted immutable user input."""
    user_input = get_find_agent_v2_service().get_run_user_input(run_id)
    return run_find_agent_v2(
        user_input,
        run_id=run_id,
        agent=agent,
        settings=settings,
        model=model,
        resume=resume,
    )
