"""SQLite storage layer for the shop bot (stdlib only)."""
import json
import os
import sqlite3
import threading
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.environ.get("SHOP_DB", os.path.join(BASE_DIR, "data", "shop.db"))

_lock = threading.RLock()
_conn = None


def now():
    return time.strftime("%Y-%m-%d %H:%M:%S")


def today():
    return time.strftime("%Y-%m-%d")


def get_conn():
    global _conn
    if _conn is None:
        os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
        _conn = sqlite3.connect(DB_PATH, timeout=30, check_same_thread=False)
        _conn.row_factory = sqlite3.Row
        _conn.execute("PRAGMA journal_mode=WAL")
        _conn.execute("PRAGMA busy_timeout=30000")
        _conn.execute("PRAGMA synchronous=NORMAL")
    return _conn


def q(sql, args=()):
    with _lock:
        cur = get_conn().execute(sql, args)
        rows = cur.fetchall()
        cur.close()
        return rows


def q1(sql, args=()):
    rows = q(sql, args)
    return rows[0] if rows else None


def x(sql, args=()):
    with _lock:
        conn = get_conn()
        cur = conn.execute(sql, args)
        conn.commit()
        last = cur.lastrowid
        cur.close()
        return last


SCHEMA = """
CREATE TABLE IF NOT EXISTS users(
    id INTEGER PRIMARY KEY,
    username TEXT,
    first_name TEXT,
    lang TEXT DEFAULT 'vi',
    balance INTEGER DEFAULT 0,
    is_admin INTEGER DEFAULT 0,
    ref_by INTEGER DEFAULT NULL,
    total_spent INTEGER DEFAULT 0,
    coupon TEXT DEFAULT NULL,
    banned INTEGER DEFAULT 0,
    created_at TEXT
);
CREATE TABLE IF NOT EXISTS categories(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    emoji TEXT DEFAULT '📦',
    sort INTEGER DEFAULT 100,
    active INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS products(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    cat_id INTEGER,
    name TEXT NOT NULL,
    price INTEGER NOT NULL,
    desc TEXT DEFAULT '',
    active INTEGER DEFAULT 1,
    sold INTEGER DEFAULT 0,
    created_at TEXT
);
CREATE TABLE IF NOT EXISTS stock(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product_id INTEGER NOT NULL,
    content TEXT NOT NULL,
    used INTEGER DEFAULT 0,
    order_id INTEGER,
    added_at TEXT
);
CREATE TABLE IF NOT EXISTS orders(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    product_id INTEGER,
    product_name TEXT,
    price INTEGER DEFAULT 0,
    discount INTEGER DEFAULT 0,
    total INTEGER DEFAULT 0,
    status TEXT DEFAULT 'done',
    content TEXT,
    created_at TEXT
);
CREATE TABLE IF NOT EXISTS invoices(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    code TEXT UNIQUE NOT NULL,
    amount INTEGER NOT NULL,
    status TEXT DEFAULT 'pending',
    method TEXT DEFAULT 'sepay',
    tx_id TEXT,
    created_at TEXT,
    paid_at TEXT
);
CREATE TABLE IF NOT EXISTS transactions(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    amount INTEGER,
    type TEXT,
    note TEXT,
    created_at TEXT
);
CREATE TABLE IF NOT EXISTS coupons(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    code TEXT UNIQUE NOT NULL,
    kind TEXT DEFAULT 'percent',
    value INTEGER DEFAULT 0,
    uses_left INTEGER DEFAULT -1,
    active INTEGER DEFAULT 1,
    created_at TEXT
);
CREATE TABLE IF NOT EXISTS settings(
    key TEXT PRIMARY KEY,
    value TEXT
);
CREATE TABLE IF NOT EXISTS states(
    user_id INTEGER PRIMARY KEY,
    state TEXT,
    data TEXT,
    updated_at TEXT
);
CREATE TABLE IF NOT EXISTS sepay_seen(
    tx_id TEXT PRIMARY KEY,
    seen_at TEXT
);
CREATE TABLE IF NOT EXISTS tickets(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    message TEXT,
    status TEXT DEFAULT 'open',
    created_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_stock_product ON stock(product_id, used);
CREATE INDEX IF NOT EXISTS idx_orders_user ON orders(user_id);
CREATE INDEX IF NOT EXISTS idx_inv_code ON invoices(code, status);
"""

DEFAULT_SETTINGS = {
    "shop_name": "Shop Tài Khoản AI",
    "bank_name": "",
    "bank_account": "",
    "bank_holder": "",
    "bank_note": "Chuyển đúng số tiền và nội dung, hệ thống tự cộng tiền sau 10-60 giây.",
    "sepay_token": "",
    "sepay_enabled": "1",
    "sepay_account": "",
    "ref_percent": "5",
    "topup_amounts": "20000,50000,100000,200000,500000",
    "support": "",
    "welcome": "",
    "min_topup": "10000",
}


def init():
    with _lock:
        conn = get_conn()
        conn.executescript(SCHEMA)
        conn.commit()
    for k, v in DEFAULT_SETTINGS.items():
        if q1("SELECT value FROM settings WHERE key=?", (k,)) is None:
            x("INSERT INTO settings(key,value) VALUES(?,?)", (k, v))
    seed_demo()


DEMO_CATS = [
    ("Công cụ AI", "🤖"), ("Thiết kế", "🎨"), ("Video", "🎬"), ("Lưu trữ", "☁️"),
    ("Lập trình", "💻"), ("Âm nhạc", "🎵"), ("Ứng dụng", "📱"), ("Giải trí", "🎮"),
    ("Giáo dục", "📚"),
]

DEMO_PRODUCTS = [
    ("AI", "Claude Pro 1 tháng", 350000),
    ("AI", "ChatGPT Plus 1 tháng", 390000),
    ("AI", "Cursor Pro 1 tháng", 350000),
    ("AI", "Grok Premium 1 tháng", 300000),
    ("Thiết kế", "Canva Pro 1 năm", 250000),
    ("Thiết kế", "Figma Pro 1 tháng", 200000),
    ("Video", "CapCut Pro 1 tháng", 150000),
    ("Lưu trữ", "Google One 100GB 1 năm", 300000),
    ("Giải trí", "Spotify Premium 1 tháng", 90000),
    ("Giải trí", "Netflix 4K 1 tháng", 120000),
]


def seed_demo():
    """First run only: fills categories + sample products (no stock) so the shop is not empty."""
    if q1("SELECT COUNT(*) c FROM categories")["c"] > 0:
        return
    ids = {}
    for i, (name, emoji) in enumerate(DEMO_CATS):
        ids[name] = x("INSERT INTO categories(name,emoji,sort,active) VALUES(?,?,?,1)",
                      (name, emoji, i * 10))
    # Products are intentionally not seeded: the owner adds real items + stock via /admin.


# ---------- settings ----------
def get_setting(key, default=""):
    row = q1("SELECT value FROM settings WHERE key=?", (key,))
    return row["value"] if row is not None else default


def set_setting(key, value):
    x("INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
      (key, str(value)))


# ---------- users ----------
def get_user(uid):
    return q1("SELECT * FROM users WHERE id=?", (uid,))


def ensure_user(uid, username="", first_name="", ref_by=None):
    u = get_user(uid)
    if u:
        x("UPDATE users SET username=?, first_name=? WHERE id=?", (username or "", first_name or "", uid))
        return get_user(uid)
    x("INSERT INTO users(id,username,first_name,lang,balance,is_admin,ref_by,created_at) VALUES(?,?,?,?,0,0,?,?)",
      (uid, username or "", first_name or "", "vi", ref_by, now()))
    return get_user(uid)


def set_lang(uid, lang):
    x("UPDATE users SET lang=? WHERE id=?", (lang, uid))


def add_balance(uid, amount, type_="adjust", note=""):
    x("UPDATE users SET balance = balance + ? WHERE id=?", (amount, uid))
    x("INSERT INTO transactions(user_id,amount,type,note,created_at) VALUES(?,?,?,?,?)",
      (uid, amount, type_, note, now()))


def set_admin(uid, flag=1):
    x("UPDATE users SET is_admin=? WHERE id=?", (flag, uid))


def get_state(uid):
    row = q1("SELECT state,data FROM states WHERE user_id=?", (uid,))
    if not row:
        return None, {}
    try:
        data = json.loads(row["data"] or "{}")
    except Exception:
        data = {}
    return row["state"], data


def set_state(uid, state, data=None):
    x("INSERT INTO states(user_id,state,data,updated_at) VALUES(?,?,?,?) "
      "ON CONFLICT(user_id) DO UPDATE SET state=excluded.state,data=excluded.data,updated_at=excluded.updated_at",
      (uid, state, json.dumps(data or {}, ensure_ascii=False), now()))


def clear_state(uid):
    x("DELETE FROM states WHERE user_id=?", (uid,))


# ---------- catalog ----------
def categories(active_only=True):
    if active_only:
        return q("SELECT * FROM categories WHERE active=1 ORDER BY sort, id")
    return q("SELECT * FROM categories ORDER BY sort, id")


def category(cid):
    return q1("SELECT * FROM categories WHERE id=?", (cid,))


def add_category(name, emoji="📦"):
    return x("INSERT INTO categories(name,emoji,sort,active) VALUES(?,?,?,1)", (name, emoji, 100))


def products_of(cat_id, page=0, per=8):
    rows = q("SELECT * FROM products WHERE cat_id=? AND active=1 ORDER BY id LIMIT ? OFFSET ?",
             (cat_id, per, page * per))
    total = q1("SELECT COUNT(*) c FROM products WHERE cat_id=? AND active=1", (cat_id,))["c"]
    return rows, total


def product(pid):
    return q1("SELECT * FROM products WHERE id=?", (pid,))


def stock_count(pid):
    row = q1("SELECT COUNT(*) c FROM stock WHERE product_id=? AND used=0", (pid,))
    return row["c"] if row else 0


def take_stock(pid, order_id):
    with _lock:
        row = q1("SELECT id,content FROM stock WHERE product_id=? AND used=0 ORDER BY id LIMIT 1", (pid,))
        if not row:
            return None
        x("UPDATE stock SET used=1, order_id=? WHERE id=?", (order_id, row["id"]))
        return row["content"]


def add_stock(pid, lines):
    added = 0
    for line in lines:
        line = line.strip()
        if not line:
            continue
        x("INSERT INTO stock(product_id,content,used,added_at) VALUES(?,?,0,?)", (pid, line, now()))
        added += 1
    return added


# ---------- orders ----------
def create_order(uid, pid, name, price, discount, total, content):
    oid = x("INSERT INTO orders(user_id,product_id,product_name,price,discount,total,status,content,created_at) "
            "VALUES(?,?,?,?,?,?,'done',?,?)", (uid, pid, name, price, discount, total, content, now()))
    x("UPDATE products SET sold = sold + 1 WHERE id=?", (pid,))
    x("UPDATE users SET total_spent = total_spent + ? WHERE id=?", (total, uid))
    return oid


def user_orders(uid, limit=10):
    return q("SELECT * FROM orders WHERE user_id=? ORDER BY id DESC LIMIT ?", (uid, limit))


# ---------- invoices ----------
def create_invoice(uid, code, amount):
    return x("INSERT INTO invoices(user_id,code,amount,status,method,created_at) VALUES(?,?,?,'pending','sepay',?)",
             (uid, code, amount, now()))


def invoice_by_code(code):
    return q1("SELECT * FROM invoices WHERE code=?", (code,))


def pending_invoices(limit=30):
    return q("SELECT * FROM invoices WHERE status='pending' ORDER BY id DESC LIMIT ?", (limit,))


def mark_invoice_paid(code, tx_id=""):
    with _lock:
        inv = invoice_by_code(code)
        if not inv or inv["status"] != "pending":
            return None
        x("UPDATE invoices SET status='paid', paid_at=?, tx_id=? WHERE id=?", (now(), tx_id, inv["id"]))
        x("UPDATE users SET balance = balance + ? WHERE id=?", (inv["amount"], inv["user_id"]))
        x("INSERT INTO transactions(user_id,amount,type,note,created_at) VALUES(?,?,?,?,?)",
          (inv["user_id"], inv["amount"], "topup", "invoice " + code, now()))
        return inv


# ---------- coupons ----------
def coupon(code):
    return q1("SELECT * FROM coupons WHERE code=? AND active=1", ((code or "").upper(),))


def use_coupon(code):
    row = coupon(code)
    if not row:
        return
    if row["uses_left"] > 0:
        left = row["uses_left"] - 1
        if left <= 0:
            x("UPDATE coupons SET uses_left=0, active=0 WHERE id=?", (row["id"],))
        else:
            x("UPDATE coupons SET uses_left=? WHERE id=?", (left, row["id"]))


# ---------- stats ----------
def stats():
    users = q1("SELECT COUNT(*) c FROM users")["c"]
    orders = q1("SELECT COUNT(*) c FROM orders")["c"]
    today_orders = q1("SELECT COUNT(*) c FROM orders WHERE created_at LIKE ?", (today() + "%",))["c"]
    revenue = q1("SELECT COALESCE(SUM(total),0) s FROM orders")["s"]
    today_rev = q1("SELECT COALESCE(SUM(total),0) s FROM orders WHERE created_at LIKE ?", (today() + "%",))["s"]
    topups = q1("SELECT COALESCE(SUM(amount),0) s FROM invoices WHERE status='paid'")["s"]
    pending = q1("SELECT COUNT(*) c FROM invoices WHERE status='pending'")["c"]
    prods = q1("SELECT COUNT(*) c FROM products WHERE active=1")["c"]
    return {
        "users": users, "orders": orders, "today_orders": today_orders,
        "revenue": revenue, "today_rev": today_rev, "topups": topups,
        "pending": pending, "products": prods,
    }
