"""Common utilities for ai-lls-lib."""

import json
from decimal import Decimal


class DecimalEncoder(json.JSONEncoder):
    """JSON encoder that handles DynamoDB Decimal types."""

    def default(self, obj: object) -> object:
        if isinstance(obj, Decimal):
            return int(obj) if obj % 1 == 0 else float(obj)
        return super().default(obj)


def extract_area_code(phone: str) -> str:
    """Extract 3-digit area code from a phone number string.

    Handles E.164 format (+1XXXXXXXXXX) and raw digits.
    Returns 'unknown' if fewer than 3 digits.
    """
    digits = "".join(c for c in phone if c.isdigit())
    if digits.startswith("1") and len(digits) >= 4:
        return digits[1:4]
    if len(digits) >= 3:
        return digits[:3]
    return "unknown"
