"""
Period / quarter-end inference.

Asks an LLM to read a table fragment and infer the reporting period it
covers (period end date plus the label as printed). Uses pydantic-ai so
it sits alongside the existing inference processor.

Value extraction is deliberately out of scope for this module.
"""

from __future__ import annotations

from datetime import date
from typing import Optional

from loguru import logger
from pydantic import BaseModel, Field

from quber.agents import AgentFactory
from quber.agents.factory import ModelProvider

PERIOD_PROMPT = """\
You are reading a financial-document table fragment to infer the
reporting period it covers.

Return a JSON object with:
- period_end (ISO date YYYY-MM-DD, or null if unknown)
- period_label (free-text label as it appears in the source, e.g.
  "Q1 FY25", "For the 3 Months Ended September 30, 2025")
- fiscal_quarter (1-4, or null)
- fiscal_year (e.g. 2025, or null)

Do not guess. If the table fragment does not state the period
unambiguously, return nulls for the fields you cannot fill.
"""


class PeriodInference(BaseModel):
    period_end: Optional[date] = Field(default=None)
    period_label: Optional[str] = Field(default=None)
    fiscal_quarter: Optional[int] = Field(default=None, ge=1, le=4)
    fiscal_year: Optional[int] = Field(default=None)


class PeriodInferenceProcessor:
    def __init__(
        self,
        provider: Optional[ModelProvider] = None,
        model: Optional[str] = None,
    ) -> None:
        factory = AgentFactory(enable_logfire=False)
        self.agent = factory.create_agent(
            output_type=PeriodInference,
            system_prompt=PERIOD_PROMPT,
            provider=provider,
            model=model,
        )

    async def infer(self, fragment: str) -> PeriodInference:
        try:
            result = await self.agent.run(fragment)
            return result.output
        except Exception as exc:
            logger.warning("PeriodInferenceProcessor failed: {exc}", exc=exc)
            return PeriodInference()
