import json
import urllib.request

ONEPAY_CONFIG = {
    "apiKey": "AIzaSyDpJzIe9IYb-NKYMKUaQJGXSFI2IPnNLTA",
    "projectId": "onepay-prod-1group"
}

def verify_payment(reference: str, amount: str = None, store_id: str = "default", env: str = "prod", project_id: str = None) -> dict:
    """
    Verify if a payment reference was confirmed by the merchant's 1pay relay.
    Supports full reference and 4/6-digit suffix matching (e.g. last 4 or 6 digits).
    """
    clean_ref = str(reference).strip()
    target_project = project_id or ("onepay-dev-1group" if env == "dev" else ONEPAY_CONFIG["projectId"])
    url = f"https://firestore.googleapis.com/v1/projects/{target_project}/databases/(default)/documents:runQuery?key={ONEPAY_CONFIG['apiKey']}"

    def query_by_field(field: str, value: str):
        payload = {
            "structuredQuery": {
                "from": [{"collectionId": "payments"}],
                "where": {
                    "fieldFilter": {
                        "field": {"fieldPath": field},
                        "op": "EQUAL",
                        "value": {"stringValue": value}
                    }
                },
                "limit": 5
            }
        }
        try:
            req = urllib.request.Request(
                url,
                data=json.dumps(payload).encode("utf-8"),
                headers={"Content-Type": "application/json"},
                method="POST"
            )
            with urllib.request.urlopen(req) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except Exception:
            return []

    def match_doc(doc):
        if not doc or "fields" not in doc:
            return None
        fields = doc["fields"]
        doc_store = fields.get("storeId", {}).get("stringValue", "default")
        if store_id and doc_store != store_id:
            return None
        doc_amount = fields.get("amount", {}).get("stringValue", "")
        if amount is not None and str(amount).strip():
            norm_doc = doc_amount.replace(",", ".")
            norm_exp = str(amount).strip().replace(",", ".")
            if norm_doc != norm_exp and doc_amount != str(amount).strip():
                return None
        return {
            "verified": True,
            "bank": fields.get("bank", {}).get("stringValue", "Unknown"),
            "reference": fields.get("reference", {}).get("stringValue", clean_ref),
            "amount": doc_amount,
            "currency": fields.get("currency", {}).get("stringValue", "VES"),
            "timestamp": fields.get("timestamp", {}).get("timestampValue")
        }

    try:
        # 1. Exact match
        for item in query_by_field("reference", clean_ref):
            m = match_doc(item.get("document"))
            if m:
                return m

        # 2. Suffix field match
        if len(clean_ref) in (4, 6):
            suffix_field = "referenceSuffix4" if len(clean_ref) == 4 else "referenceSuffix6"
            for item in query_by_field(suffix_field, clean_ref):
                m = match_doc(item.get("document"))
                if m:
                    return m

            # 3. Fallback: inspect recent payments
            recent_payload = {
                "structuredQuery": {
                    "from": [{"collectionId": "payments"}],
                    "limit": 25
                }
            }
            req = urllib.request.Request(
                url,
                data=json.dumps(recent_payload).encode("utf-8"),
                headers={"Content-Type": "application/json"},
                method="POST"
            )
            with urllib.request.urlopen(req) as resp:
                recent_list = json.loads(resp.read().decode("utf-8"))
            for item in recent_list:
                f = item.get("document", {}).get("fields", {})
                ref = f.get("reference", {}).get("stringValue", "")
                if ref.endswith(clean_ref):
                    m = match_doc(item.get("document"))
                    if m:
                        return m
    except Exception as err:
        print(f"[1pay SDK] Verification error: {err}")

    return {"verified": False}
