from __future__ import annotations

import re
from typing import Any, Dict


_COMPACT_RE = re.compile(r"[^A-Z0-9]+")
_PATTERNS = (
    re.compile(r"^Q([1-4])FY(\d{2,4})$"),
    re.compile(r"^FY(\d{2,4})Q([1-4])$"),
    re.compile(r"^([1-4])Q(\d{2,4})$"),
    re.compile(r"^(\d{2,4})Q([1-4])$"),
)


def _normalize_year(year_text: str) -> str:
    year = str(year_text or "").strip()
    if len(year) == 4:
        year = year[-2:]
    return year.zfill(2) if len(year) == 2 else ""


def normalize_fiscal_quarter(value: Any) -> Dict[str, Any]:
    raw = str(value or "").strip().upper()
    if not raw:
        return {"value": ""}

    compact = _COMPACT_RE.sub("", raw)
    for pattern in _PATTERNS:
        match = pattern.match(compact)
        if not match:
            continue

        left, right = match.groups()
        if pattern.pattern.startswith("^Q") or pattern.pattern.startswith("^([1-4])Q"):
            quarter = left
            year = right
        else:
            year = left
            quarter = right

        normalized_year = _normalize_year(year)
        if normalized_year:
            return {"value": f"FY{normalized_year}-Q{quarter}"}

    return {"value": ""}
