"""Summary Parser Agent

Refines and parses summaries to be more concise and well-structured.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Annotated

from pydantic import Field

from ..schema import ParsedSummaryOutput, 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 SummaryParserAgent:
    """Agent that refines summaries to be more concise and clear"""

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

        Args:
            config: LLM configuration
        """
        self.base = BaseAgentImpl(
            name="SummaryParser",
            description="Refines summaries to be more concise and clear",
            config=config,
        )

    async def parse(
        self,
        summary: SummaryOutput,
        output_parser: OutputParserAgent,
    ) -> AgentResponse[ParsedSummaryOutput]:
        """Parse and refine a summary to be more concise

        Args:
            summary: Raw summary output from summarizer
            project_id: Project/repository ID
            merge_id: Merge request/pull request ID
            output_parser: Output parser agent for fixing invalid JSON responses

        Returns:
            AgentResponse with parsed output and token usage

        Raises:
            ReviewateError: If parsing fails
        """
        # Build context with the summary to refine
        ctx = {
            "summary": summary.model_dump_json(),
        }

        # Load system prompt template
        template = self.base.load_prompt("summary_parser.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(ParsedSummaryOutput)

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

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

        Reads summary from ctx, parses and refines it.
        """
        if ctx.summary is None:
            raise ValueError("summary must be set before running summary parser")

        logger.info("Starting SummaryParser")
        result = await self.parse(
            summary=ctx.summary,
            output_parser=output_parser,
        )

        ctx.parsed_summary = result.output
        ctx.track("summary_parser", result.metadata)
        logger.info("SummaryParser completed")
