"""
bot/db.py — SQLite database for license & user management
"""

import sqlite3
from pathlib import Path
from datetime import datetime

DB_PATH = Path(__file__).parent / "licenses.db"


def _conn():
    conn = sqlite3.connect(str(DB_PATH), timeout=10)
    conn.row_factory = sqlite3.Row
    return conn


def init_db():
    with _conn() as c:
        c.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id              INTEGER PRIMARY KEY AUTOINCREMENT,
                telegram_id     INTEGER UNIQUE,
                telegram_name   TEXT,
                hwid            TEXT,
                email           TEXT,
                license_key     TEXT,
                plan            TEXT,
                activated_at    TEXT,
                expires_at      TEXT,
                is_active       INTEGER DEFAULT 1,
                notes           TEXT,
                created_at      TEXT DEFAULT CURRENT_TIMESTAMP
            )
        """)
        c.execute("CREATE INDEX IF NOT EXISTS idx_tg ON users(telegram_id)")
        c.execute("CREATE INDEX IF NOT EXISTS idx_key ON users(license_key)")
        c.execute("CREATE INDEX IF NOT EXISTS idx_hwid ON users(hwid)")


def upsert_user(telegram_id: int, name: str) -> int:
    with _conn() as c:
        r = c.execute("SELECT id FROM users WHERE telegram_id = ?", (telegram_id,)).fetchone()
        if r:
            c.execute("UPDATE users SET telegram_name = ? WHERE telegram_id = ?", (name, telegram_id))
            return r["id"]
        cur = c.execute(
            "INSERT INTO users (telegram_id, telegram_name) VALUES (?, ?)",
            (telegram_id, name),
        )
        return cur.lastrowid


def set_license(telegram_id: int, license_key: str, plan: str, expires_at: str, hwid: str = ""):
    with _conn() as c:
        c.execute("""
            UPDATE users SET
                license_key = ?, plan = ?, expires_at = ?,
                hwid = COALESCE(NULLIF(?, ''), hwid),
                activated_at = ?,
                is_active = 1
            WHERE telegram_id = ?
        """, (license_key, plan, expires_at, hwid, datetime.utcnow().isoformat(), telegram_id))


def get_user(telegram_id: int) -> dict | None:
    with _conn() as c:
        r = c.execute("SELECT * FROM users WHERE telegram_id = ?", (telegram_id,)).fetchone()
        return dict(r) if r else None


def list_users(limit: int = 50) -> list[dict]:
    with _conn() as c:
        rows = c.execute(
            "SELECT * FROM users ORDER BY created_at DESC LIMIT ?", (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


def ban_user(telegram_id: int):
    with _conn() as c:
        c.execute("UPDATE users SET is_active = 0 WHERE telegram_id = ?", (telegram_id,))


def unban_user(telegram_id: int):
    with _conn() as c:
        c.execute("UPDATE users SET is_active = 1 WHERE telegram_id = ?", (telegram_id,))


def count_users() -> dict:
    with _conn() as c:
        total = c.execute("SELECT COUNT(*) AS n FROM users").fetchone()["n"]
        active = c.execute("SELECT COUNT(*) AS n FROM users WHERE is_active = 1").fetchone()["n"]
        return {"total": total, "active": active}


init_db()