import aiosqlite
import os

DB_PATH = "bot_data.db"


async def init_db():
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("""
            CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY, value TEXT
            )
        """)
        await db.execute("""
            CREATE TABLE IF NOT EXISTS sent_videos (
                video_id TEXT PRIMARY KEY, platform TEXT,
                title TEXT, sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        await db.execute("""
            CREATE TABLE IF NOT EXISTS admins (
                user_id INTEGER PRIMARY KEY, name TEXT,
                added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        await db.commit()


async def get_setting(key, default=None):
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute("SELECT value FROM settings WHERE key=?", (key,))
        row = await cur.fetchone()
        return row[0] if row else default


async def set_setting(key, value):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR REPLACE INTO settings (key,value) VALUES (?,?)",
            (key, value)
        )
        await db.commit()


async def is_video_sent(video_id):
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute(
            "SELECT 1 FROM sent_videos WHERE video_id=?", (video_id,)
        )
        return await cur.fetchone() is not None


async def mark_video_sent(video_id, platform, title):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR IGNORE INTO sent_videos (video_id,platform,title) VALUES (?,?,?)",
            (video_id, platform, title)
        )
        await db.commit()


async def is_admin(user_id):
    admin_id = int(os.getenv("ADMIN_TELEGRAM_ID", "0"))
    if user_id == admin_id:
        return True
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute(
            "SELECT 1 FROM admins WHERE user_id=?", (user_id,)
        )
        return await cur.fetchone() is not None


async def add_admin(user_id, name):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR IGNORE INTO admins (user_id,name) VALUES (?,?)",
            (user_id, name)
        )
        await db.commit()


async def remove_admin(user_id):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("DELETE FROM admins WHERE user_id=?", (user_id,))
        await db.commit()


async def get_all_settings():
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute("SELECT key,value FROM settings")
        return {r[0]: r[1] for r in await cur.fetchall()}


