# -*- coding: utf-8 -*-
"""پیش‌نویسِ پست در حال ساخت هر ادمین را نگه می‌دارد (چون Flask بی‌حالته و بین وبهوک‌ها
چیزی در حافظه نمی‌ماند، وضعیتِ مکالمه باید در دیتابیس ذخیره شود)."""

import sqlite3
import time
from contextlib import contextmanager

import config

DB_PATH = config.DB_PATH


@contextmanager
def get_conn():
    conn = sqlite3.connect(DB_PATH, timeout=15)
    conn.row_factory = sqlite3.Row
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def init_db():
    with get_conn() as conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS drafts (
                admin_id              INTEGER PRIMARY KEY,
                step                  TEXT NOT NULL DEFAULT 'idle',
                content_chat_id       INTEGER,
                content_message_id    INTEGER,
                content_kind          TEXT,             -- 'text' | 'photo' | 'video' | 'animation' | ...
                button_text           TEXT,
                button_icon_emoji_id  TEXT,
                button_url            TEXT,
                button_style          TEXT,             -- 'danger' | 'success' | 'primary' | NULL
                channel_id            INTEGER,          -- کانال مقصدِ همین پست (بعد از انتخاب ادمین)
                updated_at            INTEGER
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS channels (
                chat_id     INTEGER PRIMARY KEY,
                title       TEXT,
                username    TEXT,
                active      INTEGER NOT NULL DEFAULT 1,
                added_at    INTEGER,
                updated_at  INTEGER
            )
        """)
        # مهاجرت خودکار: اگر drafts از نسخه‌ی قبل از قابلیت چندکاناله روی دیسک مانده و ستون
        # channel_id را ندارد، این‌جا اضافه‌اش می‌کنیم تا با schema جدید ناسازگار نشود.
        existing_cols = {row["name"] for row in conn.execute("PRAGMA table_info(drafts)").fetchall()}
        if "channel_id" not in existing_cols:
            conn.execute("ALTER TABLE drafts ADD COLUMN channel_id INTEGER")


# ---------------------------------------------------------------------------
# کانال‌هایی که ربات ادمینشان است (خودکار از my_chat_member، یا دستی با فوروارد پیام)
# ---------------------------------------------------------------------------

def upsert_channel(chat_id, title, username, active=1):
    with get_conn() as conn:
        conn.execute(
            """INSERT INTO channels (chat_id, title, username, active, added_at, updated_at)
               VALUES (?, ?, ?, ?, ?, ?)
               ON CONFLICT(chat_id) DO UPDATE SET
                    title=excluded.title, username=excluded.username, active=excluded.active,
                    updated_at=excluded.updated_at""",
            (chat_id, title, username, active, int(time.time()), int(time.time())),
        )


def deactivate_channel(chat_id):
    with get_conn() as conn:
        conn.execute("UPDATE channels SET active = 0, updated_at = ? WHERE chat_id = ?", (int(time.time()), chat_id))


def list_active_channels():
    with get_conn() as conn:
        rows = conn.execute("SELECT * FROM channels WHERE active = 1 ORDER BY title").fetchall()
        return [dict(r) for r in rows]


def get_channel(chat_id):
    with get_conn() as conn:
        row = conn.execute("SELECT * FROM channels WHERE chat_id = ?", (chat_id,)).fetchone()
        return dict(row) if row else None


def get_draft(admin_id):
    with get_conn() as conn:
        row = conn.execute("SELECT * FROM drafts WHERE admin_id = ?", (admin_id,)).fetchone()
        return dict(row) if row else None


def reset_draft(admin_id, step="idle"):
    with get_conn() as conn:
        conn.execute(
            """INSERT INTO drafts (admin_id, step, content_chat_id, content_message_id, content_kind,
                                    button_text, button_icon_emoji_id, button_url, button_style, channel_id, updated_at)
               VALUES (?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?)
               ON CONFLICT(admin_id) DO UPDATE SET
                    step=excluded.step, content_chat_id=NULL, content_message_id=NULL, content_kind=NULL,
                    button_text=NULL, button_icon_emoji_id=NULL, button_url=NULL, button_style=NULL,
                    channel_id=NULL, updated_at=excluded.updated_at""",
            (admin_id, step, int(time.time())),
        )


def update_draft(admin_id, **fields):
    if not fields:
        return
    fields["updated_at"] = int(time.time())
    cols = ", ".join(f"{k} = ?" for k in fields)
    values = list(fields.values()) + [admin_id]
    with get_conn() as conn:
        conn.execute(f"UPDATE drafts SET {cols} WHERE admin_id = ?", values)
