# utilities/field_mapping.py
from typing import Dict

def map_fields(service: str, fields: Dict[str, str]) -> str:
    """
    Normalize UI fields -> single 'number' expected by provider for BillFetch/BillPay.
    We are intentionally IGNORING any optional/secondary identifiers.
    """
    f = {k: (v or "").strip() for k, v in (fields or {}).items()}
    s = (service or "").strip().lower()

    def pick(*keys: str) -> str:
        for k in keys:
            v = f.get(k, "")
            if v:
                return v
        return ""

    if s in ("postpaid", "mobile", "mobile_postpaid"):
        return pick("mobile")

    if s in ("fastag", "fast tag"):
        plate = pick("vehicle_number", "vehicle_no", "vehicleno", "number")
        return plate.upper().replace(" ", "")

    if s == "electricity":
        return pick("account_id", "usn", "consumer_no", "ca_number")

    if s == "landline":
        # provider usually wants the phone number; we ignore STD here
        return str(str(pick("std_code")) + str(pick("phone_no", "landline"))).strip()

    if s == "broadband":
        return pick("account_no", "subscriber_id")

    if s == "gas":
        mode = pick("book_using").lower()
        if mode == "mobile number":
            return pick("mobile")
        if mode in ("consumer id", "consumer number"):
            return pick("consumer_id", "consumer_no")
        return pick("consumer_id", "consumer_no", "mobile")

    if s == "insurance":
        return pick("policy_no")

    if s == "loan":
        return pick("loan_account_no")

    if s == "water":
        return pick("consumer_no", "account_id")

    if s == "lpg":
        mode = pick("book_using").lower()
        if mode == "consumer id":
            return pick("consumer_id", "consumer_no")
        return pick("mobile")

    if s == "playcode":
        return pick("play_code")

    if s == "dth":
        return pick("subscriber_id")
    
    # generic fallback
    return pick("number", "account_no", "id")
