"""
ado_test_cases.py — Agent 1 pipeline: generate and link test cases for an ADO work item.

Delegates entirely to qa-test-case-manager.
The agent server owns all test-case generation logic; this module only defines
the task and the stop conditions the LLM must respect.
"""
from __future__ import annotations

import logging

from ..agent_runner import run_agent_loop
from ..models import PipelineResult, WebhookEvent
from ._base import event_env, mcp_servers

logger = logging.getLogger("stlc.pipeline.ado_test_cases")


def _task_prompt(event: WebhookEvent) -> str:
    wi_type = (event.work_item_type or "").lower()
    feature_note = (
        "This is a Feature work item. The tool will return confirmation_required=true — "
        "treat it as auto-confirmed and proceed to create_and_link_test_cases.\n"
        if wi_type == "feature" else ""
    )
    return (
        f"You are a QA automation agent running in webhook mode — auto-confirm all prompts.\n\n"
        f"Task: Generate and link test cases for ADO work item {event.work_item_id}.\n"
        f"  Organisation: {event.organization_url}\n"
        f"  Project:      {event.project_name}\n"
        f"  Type:         {event.work_item_type}\n"
        f"  State:        {event.state}\n"
        f"{feature_note}\n"
        f"Use the qa-test-case-manager tools to complete this task.\n\n"
        f"Stop immediately if:\n"
        f"  - The work item is an Epic (tool returns epic_not_supported)\n"
        f"  - Linked test cases already exist (get_linked_test_cases returns non-empty list)\n"
    )


async def run(event: WebhookEvent) -> PipelineResult:
    label = f"ado-test-cases: wi={event.work_item_id}"
    success, error = await run_agent_loop(
        mcp_config=mcp_servers("qa-test-case-manager"),
        prompt=_task_prompt(event),
        llm_provider=event.llm_provider,
        llm_model=event.llm_model,
        llm_api_key=event.llm_api_key,
        llm_base_url=event.llm_base_url,
        env=event_env(event),
        work_item_id=event.work_item_id,
    )
    if not success:
        return PipelineResult(success=False, steps=[label], error=error)
    return PipelineResult(success=True, steps=[label, "completed"])
