"""SePay auto top-up: polls SePay transactions and credits matching invoices.

The SePay token / account never leave the admin settings: users only ever see
the bank account + transfer content they must use.
"""
import json
import re
import threading
import time
import urllib.parse
import urllib.request

import db
import i18n
import tg

API = "https://my.sepay.vn/userapi/transactions/list"
CODE_RE = re.compile(r"NAP[0-9A-Z]{4,12}")
_wake = threading.Event()


def _fetch(token, account, limit=50):
    params = {"limit": str(limit)}
    if account:
        params["account_number"] = account
    url = API + "?" + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, headers={
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json",
        "Accept": "application/json",
    })
    with urllib.request.urlopen(req, timeout=20) as r:
        return json.loads(r.read().decode("utf-8"))


def _int(v):
    try:
        return int(float(str(v).replace(",", "").strip()))
    except Exception:
        return 0


def process_once(notify=True):
    token = db.get_setting("sepay_token", "").strip()
    if not token or db.get_setting("sepay_enabled", "1") != "1":
        return 0
    account = db.get_setting("sepay_account", "").strip()
    try:
        data = _fetch(token, account)
    except Exception as e:
        print("[sepay] fetch error:", e)
        return 0

    txs = data.get("transactions") or data.get("data") or []
    if isinstance(txs, dict):
        txs = txs.get("transactions", [])
    credits = 0
    for tx in txs:
        try:
            tx_id = str(tx.get("id") or tx.get("transaction_id") or "")
            if not tx_id:
                continue
            if db.q1("SELECT tx_id FROM sepay_seen WHERE tx_id=?", (tx_id,)):
                continue
            amount = _int(tx.get("amount_in") or tx.get("amount") or 0)
            if amount <= 0:
                continue
            raw = " ".join(str(tx.get(k) or "") for k in
                           ("transaction_content", "content", "code", "reference_number",
                            "reference_code", "description"))
            up = raw.upper().replace(" ", "")
            m = CODE_RE.search(up)
            if not m:
                db.x("INSERT OR IGNORE INTO sepay_seen(tx_id,seen_at) VALUES(?,?)", (tx_id, db.now()))
                continue
            code = m.group(0)
            inv = db.invoice_by_code(code)
            if inv and inv["status"] == "pending" and amount >= inv["amount"]:
                paid = db.mark_invoice_paid(code, tx_id)
                if paid:
                    credits += 1
                    if notify:
                        u = db.get_user(paid["user_id"])
                        lang = (u["lang"] if u else "vi") or "vi"
                        bal = db.get_user(paid["user_id"])["balance"]
                        tg.send(paid["user_id"], i18n.t(
                            lang, "topup_paid",
                            amount=i18n.money(paid["amount"]),
                            balance=i18n.money(bal)))
                        for adm in db.q("SELECT id FROM users WHERE is_admin=1"):
                            tg.send(adm["id"], "💰 Nạp tiền tự động: user <code>%s</code> · %s · mã %s"
                                    % (paid["user_id"], i18n.money(paid["amount"]), code))
            db.x("INSERT OR IGNORE INTO sepay_seen(tx_id,seen_at) VALUES(?,?)", (tx_id, db.now()))
        except Exception as e:
            print("[sepay] tx error:", e)
    return credits


def run_forever():
    while True:
        try:
            process_once()
        except Exception as e:
            print("[sepay] loop error:", e)
        _wake.wait(20)
        _wake.clear()


def kick():
    _wake.set()


def start():
    th = threading.Thread(target=run_forever, daemon=True, name="sepay")
    th.start()
    return th
