import json
import os

from db.database import conn, cursor

VS_FILE = "data/vs_configs.json"
MIGRATION_KEY = "vs_configs_json_migrated"


def _default_config():
    return {
        "caption": "",
        "image": "",
        "prices": []
    }


def _get_setting(key):
    cursor.execute("SELECT value FROM settings WHERE key = ?", (key,))
    row = cursor.fetchone()
    return row[0] if row else None


def _set_setting(key, value):
    cursor.execute("""
        INSERT INTO settings (key, value) VALUES (?, ?)
        ON CONFLICT(key) DO UPDATE SET value = excluded.value
    """, (key, value))
    conn.commit()


def _normalize_config(config):
    if not isinstance(config, dict):
        return _default_config()
    prices = config.get("prices", [])
    if not isinstance(prices, list):
        prices = []
    return {
        "caption": config.get("caption", "") or "",
        "image": config.get("image", "") or "",
        "prices": prices
    }


def _row_to_config(row):
    try:
        prices = json.loads(row["prices_json"] or "[]")
    except Exception:
        prices = []
    return {
        "caption": row["caption"] or "",
        "image": row["image"] or "",
        "prices": prices if isinstance(prices, list) else []
    }


def _save_config_row(admin_id, config):
    config = _normalize_config(config)
    cursor.execute("""
        INSERT INTO vs_configs (admin_id, caption, image, prices_json)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(admin_id) DO UPDATE SET
            caption = excluded.caption,
            image = excluded.image,
            prices_json = excluded.prices_json,
            updated_at = datetime('now', 'localtime')
    """, (
        int(admin_id),
        config["caption"],
        config["image"],
        json.dumps(config["prices"], ensure_ascii=False)
    ))


def _migrate_json_if_needed():
    if _get_setting(MIGRATION_KEY) == "1":
        return

    if os.path.exists(VS_FILE):
        try:
            with open(VS_FILE, "r", encoding="utf-8") as f:
                raw = json.load(f)
        except Exception:
            raw = {}

        if isinstance(raw, dict):
            for admin_id, config in raw.items():
                try:
                    _save_config_row(int(admin_id), config)
                except (TypeError, ValueError):
                    continue
            conn.commit()

    _set_setting(MIGRATION_KEY, "1")


def load_vs():
    _migrate_json_if_needed()
    cursor.execute("SELECT * FROM vs_configs ORDER BY admin_id")
    return {str(row["admin_id"]): _row_to_config(row) for row in cursor.fetchall()}


def save_vs(data):
    cursor.execute("DELETE FROM vs_configs")
    for admin_id, config in data.items():
        _save_config_row(admin_id, config)
    conn.commit()
    _set_setting(MIGRATION_KEY, "1")


def get_vs(admin_id):
    _migrate_json_if_needed()
    cursor.execute("SELECT * FROM vs_configs WHERE admin_id = ?", (int(admin_id),))
    row = cursor.fetchone()
    return _row_to_config(row) if row else None


def save_vs_config(admin_id, config):
    _migrate_json_if_needed()
    _save_config_row(admin_id, config)
    conn.commit()


def add_vs_package(admin_id, nama, harga):
    admin_id = str(admin_id)
    config = get_vs(admin_id) or _default_config()

    config["prices"].append({
        "nama": nama,
        "harga": harga
    })

    save_vs_config(admin_id, config)

def set_vs_image(admin_id, file_id):
    admin_id = str(admin_id)
    config = get_vs(admin_id) or _default_config()
    config["image"] = file_id

    save_vs_config(admin_id, config)

def delete_vs_package(admin_id, index):
    admin_id = str(admin_id)
    config = get_vs(admin_id)
    if not config:
        return False
    prices = config.get("prices", [])
    if index < 0 or index >= len(prices):
        return False
    prices.pop(index)
    config["prices"] = prices
    save_vs_config(admin_id, config)
    return True


def set_vs_caption(admin_id, caption):
    admin_id = str(admin_id)
    config = get_vs(admin_id) or _default_config()
    config["caption"] = caption

    save_vs_config(admin_id, config)
