"""Provider pattern analysis chain builder (cross-claim)."""
from __future__ import annotations
from typing import Any, Literal
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableSerializable
from pydantic import BaseModel, Field
from claim_validator.chains.base import build_chain
from claim_validator.chains.memory.manager import MemoryManager, MemoryType

class ProviderPatternOutput(BaseModel):
    recurring_issues: list[str] = Field(default_factory=list)
    risk_level: Literal["low", "medium", "high"] = "low"
    recommendation: str = ""

_parser = PydanticOutputParser(pydantic_object=ProviderPatternOutput)

PROVIDER_PATTERN_PROMPT = ChatPromptTemplate.from_messages([
    ("system", "You are analyzing claim validation patterns for a specific provider. "
     "Summarize recurring issues and flag systemic concerns.\n\n{format_instructions}"),
    MessagesPlaceholder("history", optional=True),
    ("human", "{findings_summary}"),
]).partial(format_instructions=_parser.get_format_instructions())

def build_provider_pattern_chain(config: dict[str, Any], memory_manager: MemoryManager | None = None) -> RunnableSerializable:
    return build_chain(prompt=PROVIDER_PATTERN_PROMPT, output_schema=ProviderPatternOutput, config=config,
                       memory_manager=memory_manager, memory_type=MemoryType.CROSS_CLAIM, input_key="findings_summary")
