import os
import sqlite3
import json
import time
from typing import Optional, Dict, Any, List
from app.config import settings

DB_PATH = os.path.join(settings.STORAGE_DIR, "sonicforge.db")

def get_db_connection():
    os.makedirs(settings.STORAGE_DIR, exist_ok=True)
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # Bảng Users
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id TEXT PRIMARY KEY,
        username TEXT UNIQUE NOT NULL,
        email TEXT UNIQUE NOT NULL,
        hashed_password TEXT NOT NULL,
        role TEXT DEFAULT 'standard',
        must_change_password BOOLEAN DEFAULT 1,
        created_at REAL NOT NULL,
        is_active BOOLEAN DEFAULT 1
    );
    """)
    
    # Bảng Quotas
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS user_quotas (
        user_id TEXT PRIMARY KEY,
        storage_limit_mb INTEGER DEFAULT 500,
        max_tracks INTEGER DEFAULT 16,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    );
    """)
    
    # Bảng Projects (Bao gồm Cloud Project & Temp Auto-Save)
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS projects (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        name TEXT NOT NULL,
        data_json TEXT NOT NULL,
        is_temp BOOLEAN DEFAULT 0,
        size_bytes INTEGER DEFAULT 0,
        updated_at REAL NOT NULL,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    );
    """)
    
    # Bảng System Flags
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS system_flags (
        flag_key TEXT PRIMARY KEY,
        description TEXT,
        is_enabled BOOLEAN DEFAULT 1,
        updated_at REAL NOT NULL
    );
    """)
    
    conn.commit()
    conn.close()

# Tự động khởi tạo DB khi module được import
init_db()
