"""Parse NAICS codes into normalized rollups."""

from __future__ import annotations

import re
from typing import Any, Dict, List, Optional

NAICS_SECTORS = {
    "11": "Agriculture, Forestry, Fishing and Hunting",
    "21": "Mining, Quarrying, and Oil and Gas Extraction",
    "22": "Utilities",
    "23": "Construction",
    "31": "Manufacturing",
    "32": "Manufacturing",
    "33": "Manufacturing",
    "42": "Wholesale Trade",
    "44": "Retail Trade",
    "45": "Retail Trade",
    "48": "Transportation and Warehousing",
    "49": "Transportation and Warehousing",
    "51": "Information",
    "52": "Finance and Insurance",
    "53": "Real Estate and Rental and Leasing",
    "54": "Professional, Scientific, and Technical Services",
    "55": "Management of Companies and Enterprises",
    "56": "Administrative and Support and Waste Management and Remediation Services",
    "61": "Educational Services",
    "62": "Health Care and Social Assistance",
    "71": "Arts, Entertainment, and Recreation",
    "72": "Accommodation and Food Services",
    "81": "Other Services (except Public Administration)",
    "92": "Public Administration",
}

NAICS_DIGITS = re.compile(r"\d")


def _normalize_naics(value: Optional[str]) -> str:
    if not value:
        return ""
    digits = "".join(NAICS_DIGITS.findall(str(value)))
    return digits[:6]


def _parse_naics(value: Optional[str]) -> List[str]:
    digits = _normalize_naics(value)
    if len(digits) < 2:
        return ["", "", ""]
    padded = digits.ljust(6, "0")
    sector_code = padded[:2]
    sector_name = NAICS_SECTORS.get(sector_code)
    if not sector_name:
        return ["", "", ""]
    naics3 = padded[:3]
    naics6 = padded
    return [
        f"{sector_code} - {sector_name}",
        f"{naics3} - {sector_name}",
        f"{naics6} - {sector_name}",
    ]


def parse_naics(value: str | None) -> Dict[str, Any]:
    parsed = _parse_naics(value)
    if parsed[0]:
        sector_code, sector_name = parsed[0].split(" - ", 1)
        meta = {
            "sector_code": sector_code,
            "sector_name": sector_name,
            "normalized": parsed[-1][:6],
        }
    else:
        meta = {"reason": "invalid", "input": value}
    return {"value": parsed, "meta": meta}
