"""
ScanLook Database Initialization - CORE ONLY
Creates only core system tables. Module tables are created when modules are installed.
"""

import sqlite3
import os
from datetime import datetime
from werkzeug.security import generate_password_hash

DB_PATH = os.path.join(os.path.dirname(__file__), 'scanlook.db')


def init_database():
    """Initialize the database with core system tables only"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # ============================================
    # CORE SYSTEM TABLES
    # ============================================
    
    # Users Table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS Users (
        user_id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL,
        full_name TEXT NOT NULL,
        email TEXT,
        role TEXT NOT NULL CHECK(role IN ('owner', 'admin', 'staff')),
        is_active INTEGER DEFAULT 1,
        branch TEXT DEFAULT 'Main',
        created_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
    )
    ''')
    
    # Modules Table (legacy - for user permissions)
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS Modules (
        module_id INTEGER PRIMARY KEY AUTOINCREMENT,
        module_name TEXT NOT NULL,
        module_key TEXT UNIQUE NOT NULL,
        description TEXT,
        icon TEXT,
        is_active INTEGER DEFAULT 1,
        display_order INTEGER DEFAULT 0
    )
    ''')
    
    # UserModules Table (module access per user)
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS UserModules (
        user_module_id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER NOT NULL,
        module_id INTEGER NOT NULL,
        granted_by INTEGER,
        granted_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES Users(user_id),
        FOREIGN KEY (module_id) REFERENCES Modules(module_id),
        FOREIGN KEY (granted_by) REFERENCES Users(user_id),
        UNIQUE(user_id, module_id)
    )
    ''')
    
    # Module Registry Table (new module manager system)
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS module_registry (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        module_key TEXT UNIQUE NOT NULL,
        name TEXT NOT NULL,
        version TEXT NOT NULL,
        author TEXT,
        description TEXT,
        is_installed INTEGER DEFAULT 0,
        is_active INTEGER DEFAULT 0,
        installed_at TEXT,
        config_json TEXT
    )
    ''')
    
    # Schema Migrations Table (for core migrations only)
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS schema_migrations (
        version INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
    ''')
    
    conn.commit()
    conn.close()
    print(f"✅ Core database initialized at: {DB_PATH}")
    print("📦 Module tables will be created when modules are installed")


def create_default_users():
    """Create default users for testing"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    default_users = [
        ('owner', generate_password_hash('owner123'), 'System Owner', 'owner'),
        ('admin', generate_password_hash('admin123'), 'Admin User', 'admin'),
        ('staff1', generate_password_hash('staff123'), 'John Doe', 'staff'),
        ('staff2', generate_password_hash('staff123'), 'Jane Smith', 'staff'),
    ]
    
    try:
        cursor.executemany('''
            INSERT INTO Users (username, password, full_name, role)
            VALUES (?, ?, ?, ?)
        ''', default_users)
        conn.commit()
        print("✅ Default users created:")
        print("   Owner: owner / owner123")
        print("   Admin: admin / admin123")
        print("   Staff: staff1 / staff123")
        print("   Staff: staff2 / staff123")
    except sqlite3.IntegrityError:
        print("ℹ️  Default users already exist")
    
    conn.close()


if __name__ == '__main__':
    init_database()
    create_default_users()
    