import requests
import logging

logger = logging.getLogger(__name__)

def lookup_mst(tax_code: str) -> dict:
    """
    Look up Tax ID info from xinvoice (first try) and vietqr (fallback).
    Returns: {"name": str, "address": str} or None if not found/error.
    """
    if not tax_code or len(tax_code.strip()) < 10:
        return None
        
    tax_code = tax_code.strip()
    
    # Try 1: XInvoice (https://api.xinvoice.vn/gdt-api/tax-payer/:taxCode)
    try:
        url_xin = f"https://api.xinvoice.vn/gdt-api/tax-payer/{tax_code}"
        res = requests.get(url_xin, timeout=5)
        if res.status_code == 200:
            data = res.json()
            if "name" in data and data["name"]:
                return {
                    "name": data.get("name", ""),
                    "address": data.get("address", "")
                }
    except Exception as e:
        logger.warning(f"XInvoice MST lookup failed for {tax_code}: {e}")

    # Try 2: VietQR (https://api.vietqr.io/v2/business/{tax_code})
    try:
        url_vqr = f"https://api.vietqr.io/v2/business/{tax_code}"
        res = requests.get(url_vqr, timeout=5)
        if res.status_code == 200:
            resp_json = res.json()
            # vietqr format: {"code":"00","desc":"Thành công","data":{"id":"...","name":"...","address":"..."}}
            if resp_json.get("code") == "00" and "data" in resp_json:
                data = resp_json["data"]
                if data and "name" in data:
                    return {
                        "name": data.get("name", ""),
                        "address": data.get("address", "")
                    }
    except Exception as e:
        logger.warning(f"VietQR MST lookup failed for {tax_code}: {e}")

    return None
