"""Summarizer Agent

Generates comprehensive summaries of merge request changes.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Annotated

from pydantic import Field

from ..schema import Issue, MergeRequest, SummaryOutput
from .base import AgentConfig, AgentResponse, BaseAgentImpl
from .output_parser import OutputParserAgent
from .utils import format_template

if TYPE_CHECKING:
    from ..workflows.context import PipelineContext

logger = logging.getLogger(__name__)


class SummarizerAgent:
    """Agent that generates summaries of merge request changes"""

    def __init__(
        self,
        config: Annotated[AgentConfig, Field(description="LLM configuration")],
    ):
        """Initialize SummarizerAgent

        Args:
            config: LLM configuration
        """
        self.base = BaseAgentImpl(
            name="Summarizer",
            description="Generates comprehensive summaries of merge request changes",
            config=config,
        )

    async def summarize(
        self,
        merge_info: MergeRequest,
        diffs: str,
        issues: list[Issue],
        output_parser: OutputParserAgent,
    ) -> AgentResponse[SummaryOutput]:
        """Generate a summary of merge request changes

        Args:
            merge_info: Merge request information
            diffs: Git diffs of the changes
            issues: List of linked issues
            output_parser: Output parser agent for fixing invalid JSON responses

        Returns:
            AgentResponse with parsed output and token usage

        Raises:
            ReviewateError: If summarization fails
        """
        # Format issues for context

        # Build context with merge request info and diffs
        ctx = {
            "title": merge_info.title,
            "description": merge_info.description,
            "target_branch": merge_info.target_branch,
            "source_branch": merge_info.source_branch,
            "diffs": diffs,
            "issues": issues,
        }

        # Load system prompt template
        template = self.base.load_prompt("summarizer_agent.txt")

        # Format system prompt
        system_prompt = format_template(self.base.jinja_env, template, ctx)

        # Add output format instructions
        output_format = self.base.get_output_format(SummaryOutput)

        # Call base analyze
        return await self.base.analyze(
            system_prompt=system_prompt,
            user_prompt=output_format,
            response_model=SummaryOutput,
            output_parser=output_parser,
        )

    async def run(
        self,
        ctx: PipelineContext,
        output_parser: OutputParserAgent,
    ) -> None:
        """Execute as a pipeline step.

        Reads merge_request and issues from ctx, generates summary.
        """
        if ctx.merge_request is None:
            raise ValueError("merge_request must be set before running summarizer")

        logger.info("Starting Summarizer")
        result = await self.summarize(
            merge_info=ctx.merge_request,
            diffs=ctx.merge_request.diffs,
            issues=ctx.issues,
            output_parser=output_parser,
        )

        ctx.summary = result.output
        ctx.track("summarizer", result.metadata)
        logger.info("Summarizer completed")
