"""
Usage-report log: records who used the bot, from where, and what they did
(pressed a button, ran /start, looked up a price, ...).

No UI is provided on purpose — query the database directly, e.g.:

    sqlite3 data/usage_log.db "SELECT * FROM usage_log ORDER BY id DESC LIMIT 50;"
    sqlite3 data/usage_log.db "SELECT action, COUNT(*) FROM usage_log GROUP BY action;"
"""

import os
import sqlite3
import threading
from datetime import datetime, timezone

from .. import config

_lock = threading.Lock()
_TABLE = "usage_log"


def _path() -> str:
    return os.path.join(config.DATA_DIR, "usage_log.db")


def _connect() -> sqlite3.Connection:
    os.makedirs(config.DATA_DIR, exist_ok=True)
    conn = sqlite3.connect(_path())
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS {_TABLE} (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            chat_id TEXT,
            first_name TEXT,
            last_name TEXT,
            action TEXT NOT NULL,
            detail TEXT,
            created_at TEXT NOT NULL
        )
        """
    )
    return conn


def log_action(chat_id, first_name, last_name, action: str, detail: str = None) -> None:
    """
    Record one usage event. Never raises — a logging failure must not break
    the bot's actual response to the user.
    """
    try:
        with _lock:
            conn = _connect()
            try:
                conn.execute(
                    f"INSERT INTO {_TABLE} (chat_id, first_name, last_name, action, detail, created_at) "
                    "VALUES (?, ?, ?, ?, ?, ?)",
                    (
                        str(chat_id) if chat_id is not None else None,
                        first_name,
                        last_name,
                        action,
                        detail,
                        datetime.now(timezone.utc).isoformat(),
                    ),
                )
                conn.commit()
            finally:
                conn.close()
    except Exception:
        pass
