"""
state.py
========

PURPOSE
-------
A bot is a CONVERSATION. The user sends a domain, then later sends a new URL,
and we must remember "this user is in the middle of editing redirect X".

THE WEBHOOK PROBLEM
-------------------
With webhooks, each Telegram update arrives as a SEPARATE HTTP request. cPanel
(via Passenger) may even handle different requests in different processes, and
it can shut your process down between requests to save memory. That means we
CANNOT just store conversation state in a normal Python variable — it would
vanish.

THE SOLUTION
------------
We persist conversation state to a tiny SQLite database file on disk. SQLite is
built into Python (no extra install), it's a single file, and it safely handles
multiple processes reading/writing at once. Perfect for cPanel.

We store, per chat:
  - step : where the user is in the flow (e.g. "awaiting_url").
  - data : a JSON blob of context (which zone/rule/list/item we're editing).
  - updated_at : a timestamp, so old/abandoned conversations can expire.
"""

import json       # To serialize the "data" dict into a string column.
import os          # To build a filesystem path next to this script.
import sqlite3     # The built-in embedded database.
import time        # For the updated_at timestamp.

# Put the database file in the SAME folder as this code, regardless of what
# the current working directory is when cPanel runs us. __file__ is the path
# to this very file; dirname() gives its folder.
_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bot_state.db")

# Conversations older than this many seconds are considered abandoned and are
# ignored / overwritten. 30 minutes is plenty for editing one redirect.
_STATE_TTL_SECONDS = 30 * 60


def _connect() -> sqlite3.Connection:
    """
    Open a connection to the SQLite database.

    We open a fresh connection per call (cheap for SQLite) which keeps things
    simple and process-safe. `check_same_thread=False` lets Flask's threaded
    server use the connection without complaints.
    """
    conn = sqlite3.connect(_DB_PATH, timeout=10, check_same_thread=False)
    # Return rows as dict-like objects so we can do row["step"] instead of
    # row[0]. More readable.
    conn.row_factory = sqlite3.Row
    return conn


def init_db() -> None:
    """
    Create the conversation table if it does not exist yet.

    This is safe to call every time the app starts — "IF NOT EXISTS" means it
    only creates the table the first time.
    """
    with _connect() as conn:
        conn.execute(
            """
            CREATE TABLE IF NOT EXISTS conversation (
                chat_id    INTEGER PRIMARY KEY,  -- one row per Telegram chat
                step       TEXT NOT NULL,         -- current step in the flow
                data       TEXT NOT NULL,         -- JSON context blob
                updated_at REAL NOT NULL          -- unix timestamp (seconds)
            )
            """
        )
        # `with _connect()` auto-commits on success.


def set_state(chat_id: int, step: str, data: dict) -> None:
    """
    Save (or overwrite) the conversation state for one chat.

    Parameters
    ----------
    chat_id : int
        The Telegram chat id (our primary key — one conversation per chat).
    step : str
        A label for where the user is, e.g. "awaiting_url" or "awaiting_confirm".
    data : dict
        Any context we need to remember (zone id, rule id, pending URL, ...).
        We JSON-encode it into a single text column.
    """
    with _connect() as conn:
        # "INSERT ... ON CONFLICT(chat_id) DO UPDATE" = upsert: insert a new row,
        # or update the existing one if this chat already has state.
        conn.execute(
            """
            INSERT INTO conversation (chat_id, step, data, updated_at)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(chat_id) DO UPDATE SET
                step = excluded.step,
                data = excluded.data,
                updated_at = excluded.updated_at
            """,
            (chat_id, step, json.dumps(data), time.time()),
        )


def get_state(chat_id: int) -> dict | None:
    """
    Load the conversation state for one chat.

    Returns
    -------
    dict with keys "step" and "data"   -> if an active (non-expired) state exists.
    None                                -> if there is no state, or it expired.
    """
    with _connect() as conn:
        row = conn.execute(
            "SELECT step, data, updated_at FROM conversation WHERE chat_id = ?",
            (chat_id,),
        ).fetchone()

    if row is None:
        return None

    # If the saved state is older than the TTL, treat it as gone.
    if time.time() - row["updated_at"] > _STATE_TTL_SECONDS:
        clear_state(chat_id)
        return None

    return {
        "step": row["step"],
        # Decode the JSON text column back into a Python dict.
        "data": json.loads(row["data"]),
    }


def clear_state(chat_id: int) -> None:
    """
    Forget everything about a chat's conversation (e.g. after finishing or
    cancelling). The next message from this chat starts fresh.
    """
    with _connect() as conn:
        conn.execute("DELETE FROM conversation WHERE chat_id = ?", (chat_id,))
