"""
Gestion de la base de données SQLite pour mkdocs-superquiz
"""

import sqlite3
import uuid


class QuizDatabase:
    def __init__(self, db_path):
        self.db_path = db_path
        self.conn = None
        self.cursor = None
        self._connect()
        self._create_tables()
    
    def _connect(self):
        self.conn = sqlite3.connect(self.db_path)
        self.cursor = self.conn.cursor()
    
    def _create_tables(self):
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS pages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                page_uuid TEXT UNIQUE NOT NULL,
                page_path TEXT NOT NULL,
                page_title TEXT,
                corrections_locked BOOLEAN DEFAULT 0
            )
        ''')
        
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS quizzes (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                page_uuid TEXT NOT NULL,
                quiz_number INTEGER NOT NULL,
                quiz_type TEXT NOT NULL,
                quiz_title TEXT,
                UNIQUE(page_uuid, quiz_number),
                FOREIGN KEY (page_uuid) REFERENCES pages(page_uuid)
            )
        ''')
        
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS questions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                quiz_id INTEGER NOT NULL,
                question_number INTEGER NOT NULL,
                question_text TEXT,
                UNIQUE(quiz_id, question_number),
                FOREIGN KEY (quiz_id) REFERENCES quizzes(id)
            )
        ''')
        
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS answers (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                question_id INTEGER NOT NULL,
                answer_text TEXT,
                is_correct BOOLEAN NOT NULL,
                answer_order INTEGER NOT NULL,
                FOREIGN KEY (question_id) REFERENCES questions(id)
            )
        ''')
        
        self.conn.commit()
    
    def get_or_create_page(self, page_path, page_title, corrections_locked=False):
        self.cursor.execute('''
            SELECT page_uuid FROM pages WHERE page_path = ?
        ''', (page_path,))
        
        result = self.cursor.fetchone()
        
        if result:
            page_uuid = result[0]
            self.cursor.execute('''
                UPDATE pages 
                SET page_title = ?, corrections_locked = ?
                WHERE page_uuid = ?
            ''', (page_title, corrections_locked, page_uuid))
            self.conn.commit()
            self._clean_page_quizzes(page_uuid)
            return page_uuid
        else:
            page_uuid = str(uuid.uuid4())
            self.cursor.execute('''
                INSERT INTO pages (page_uuid, page_path, page_title, corrections_locked)
                VALUES (?, ?, ?, ?)
            ''', (page_uuid, page_path, page_title, corrections_locked))
            self.conn.commit()
            return page_uuid
    
    def get_page_by_uuid(self, page_uuid):
        self.cursor.execute('''
            SELECT page_uuid, page_path, page_title, corrections_locked
            FROM pages
            WHERE page_uuid = ?
        ''', (page_uuid,))
        
        result = self.cursor.fetchone()
        
        if result:
            return {
                'page_uuid': result[0],
                'page_path': result[1],
                'page_title': result[2],
                'corrections_locked': bool(result[3])
            }
        
        return None

    def _clean_page_quizzes(self, page_uuid):
        self.cursor.execute('''
            SELECT id FROM quizzes WHERE page_uuid = ?
        ''', (page_uuid,))
        
        quiz_ids = [row[0] for row in self.cursor.fetchall()]
        
        for quiz_id in quiz_ids:
            self.cursor.execute('''
                SELECT id FROM questions WHERE quiz_id = ?
            ''', (quiz_id,))
            
            question_ids = [row[0] for row in self.cursor.fetchall()]
            
            for question_id in question_ids:
                self.cursor.execute('''
                    DELETE FROM answers WHERE question_id = ?
                ''', (question_id,))
            
            self.cursor.execute('''
                DELETE FROM questions WHERE quiz_id = ?
            ''', (quiz_id,))
        
        self.cursor.execute('''
            DELETE FROM quizzes WHERE page_uuid = ?
        ''', (page_uuid,))
        
        self.conn.commit()
    
    def add_quiz(self, page_uuid, quiz_number, quiz_type, quiz_title):
        self.cursor.execute('''
            INSERT INTO quizzes (page_uuid, quiz_number, quiz_type, quiz_title)
            VALUES (?, ?, ?, ?)
        ''', (page_uuid, quiz_number, quiz_type, quiz_title))
        
        self.conn.commit()
        return self.cursor.lastrowid
    
    def add_question(self, quiz_id, question_number, question_text):
        self.cursor.execute('''
            INSERT INTO questions (quiz_id, question_number, question_text)
            VALUES (?, ?, ?)
        ''', (quiz_id, question_number, question_text))
        
        self.conn.commit()
        return self.cursor.lastrowid
    
    def add_answer(self, question_id, answer_text, is_correct, answer_order):
        self.cursor.execute('''
            INSERT INTO answers (question_id, answer_text, is_correct, answer_order)
            VALUES (?, ?, ?, ?)
        ''', (question_id, answer_text, is_correct, answer_order))
        
        self.conn.commit()
        return self.cursor.lastrowid
    
    def close(self):
        if self.conn:
            self.conn.close()
    
    def __del__(self):
        self.close()

