"""Parse Standard Industrial Classification (SIC) codes."""

from __future__ import annotations

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

SIC_DIVISIONS = [
    ("A", 1, 9, "Agriculture, Forestry, and Fishing"),
    ("B", 10, 14, "Mining"),
    ("C", 15, 17, "Construction"),
    ("D", 20, 39, "Manufacturing"),
    (
        "E",
        40,
        49,
        "Transportation, Communications, Electric, Gas, and Sanitary Services",
    ),
    ("F", 50, 51, "Wholesale Trade"),
    ("G", 52, 59, "Retail Trade"),
    ("H", 60, 67, "Finance, Insurance, and Real Estate"),
    ("I", 70, 89, "Services"),
    ("J", 90, 99, "Public Administration"),
]

NON_DIGIT_RE = re.compile(r"\D")


def _division_for(code: int) -> Optional[Dict[str, Any]]:
    for division, start, end, name in SIC_DIVISIONS:
        if start <= code <= end:
            return {"division": division, "name": name, "start": start, "end": end}
    return None


def _normalize_sic(value: Optional[str]) -> str:
    if not value:
        return ""
    digits = NON_DIGIT_RE.sub("", str(value))
    return digits[:4]


def _parse_sic(value: Optional[str]) -> List[str]:
    digits = _normalize_sic(value)
    if len(digits) < 2:
        return ["", ""]
    padded = digits.ljust(4, "0")
    sic2 = padded[:2]
    division = _division_for(int(sic2))
    if not division:
        return ["", ""]
    label = f"Division {division['division']} ({division['name']})"
    return [f"{sic2} - {label}", f"{padded} - {label}"]


def parse_sic(value: str | None) -> Dict[str, Any]:
    parsed = _parse_sic(value)
    if parsed[0]:
        division = parsed[0].split(" - ", 1)[1]
        meta = {"division": division, "normalized": parsed[-1][:4]}
    else:
        meta = {"reason": "invalid", "input": value}
    return {"value": parsed, "meta": meta}
