"""
jira_test_cases.py — Agent 5 pipeline: generate and link test cases for a Jira issue.

Delegates entirely to qa-jira-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.jira_test_cases")


def _task_prompt(event: WebhookEvent) -> str:
    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 Jira issue {event.work_item_id}.\n"
        f"  Cloud ID:    {event.cloud_id}\n"
        f"  Project:     {event.project_key}\n"
        f"  Type:        {event.work_item_type}\n"
        f"  Status:      {event.state}\n\n"
        f"Use the qa-jira-manager tools to complete this task.\n\n"
        f"Stop immediately if:\n"
        f"  - The issue type is 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"jira-test-cases: wi={event.work_item_id}"
    success, error = await run_agent_loop(
        mcp_config=mcp_servers("qa-jira-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"])
