-- Subjects (e.g., "Computer Science", "Art History")
CREATE TABLE IF NOT EXISTS subjects (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    color TEXT,
    priority INTEGER DEFAULT 0
);

-- Topics within subjects (e.g., "Algorithms", "Data Structures")
CREATE TABLE IF NOT EXISTS topics (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject_id INTEGER NOT NULL REFERENCES subjects(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(subject_id, name)
);

-- Study cards/items within topics
CREATE TABLE IF NOT EXISTS cards (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    topic_id INTEGER NOT NULL REFERENCES topics(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    key_points TEXT,
    card_type TEXT DEFAULT 'concept',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    -- SM-2 Spaced Repetition Fields
    easiness_factor REAL DEFAULT 2.5,
    interval_days INTEGER DEFAULT 0,
    repetitions INTEGER DEFAULT 0,
    next_review DATE,
    last_review TIMESTAMP
);

-- Study sessions
CREATE TABLE IF NOT EXISTS sessions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject_id INTEGER REFERENCES subjects(id),
    topic_id INTEGER REFERENCES topics(id),
    session_type TEXT NOT NULL,
    started_at TIMESTAMP NOT NULL,
    ended_at TIMESTAMP,
    planned_duration_minutes INTEGER NOT NULL,
    actual_duration_seconds INTEGER,
    completed BOOLEAN DEFAULT FALSE,
    output_submitted BOOLEAN DEFAULT FALSE,
    output_content TEXT,

    -- Time tracking
    active_seconds INTEGER DEFAULT 0,
    idle_seconds INTEGER DEFAULT 0,

    -- Eye tracking stats
    focus_percentage REAL,
    distraction_count INTEGER DEFAULT 0,
    penalty_seconds INTEGER DEFAULT 0,
    eye_tracking_enabled BOOLEAN DEFAULT FALSE
);

-- Eye tracking events
CREATE TABLE IF NOT EXISTS eye_tracking_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,
    event_type TEXT NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    duration_seconds REAL,
    gaze_direction TEXT
);

-- Recall attempts
CREATE TABLE IF NOT EXISTS recall_attempts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,
    card_id INTEGER REFERENCES cards(id) ON DELETE CASCADE,
    recall_type TEXT NOT NULL,
    user_response TEXT NOT NULL,

    -- AI scoring
    score REAL,
    key_points_recalled TEXT,
    key_points_missed TEXT,
    ai_feedback TEXT,

    -- SM-2 quality rating
    quality_rating INTEGER,

    -- Eye tracking penalty
    focus_penalty REAL DEFAULT 0.0,
    final_adjusted_score REAL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Scheduled study blocks
CREATE TABLE IF NOT EXISTS schedule (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject_id INTEGER REFERENCES subjects(id),
    topic_id INTEGER REFERENCES topics(id),
    scheduled_at TIMESTAMP NOT NULL,
    duration_minutes INTEGER NOT NULL,
    session_type TEXT NOT NULL,
    completed BOOLEAN DEFAULT FALSE,
    missed BOOLEAN DEFAULT FALSE,
    reminder_sent BOOLEAN DEFAULT FALSE,
    escalation_level INTEGER DEFAULT 0
);

-- Streaks and gamification
CREATE TABLE IF NOT EXISTS streaks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject_id INTEGER REFERENCES subjects(id),
    current_streak INTEGER DEFAULT 0,
    longest_streak INTEGER DEFAULT 0,
    last_study_date DATE,
    total_xp INTEGER DEFAULT 0,
    daily_xp INTEGER DEFAULT 0,
    daily_xp_goal INTEGER DEFAULT 100,
    level INTEGER DEFAULT 1
);

-- Time tracking (granular)
CREATE TABLE IF NOT EXISTS time_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,
    activity_type TEXT NOT NULL,
    started_at TIMESTAMP NOT NULL,
    ended_at TIMESTAMP,
    duration_seconds INTEGER
);

-- Blocked apps/sites configuration
CREATE TABLE IF NOT EXISTS blocked_items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    item_type TEXT NOT NULL,
    item_value TEXT NOT NULL,
    active BOOLEAN DEFAULT TRUE
);

-- Stakes/penalties configuration
CREATE TABLE IF NOT EXISTS stakes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    description TEXT,
    trigger_type TEXT NOT NULL,
    action_type TEXT NOT NULL,
    action_config TEXT,
    active BOOLEAN DEFAULT TRUE
);

-- Email notification log
CREATE TABLE IF NOT EXISTS notifications (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    notification_type TEXT NOT NULL,
    recipient TEXT NOT NULL,
    subject TEXT,
    body TEXT,
    sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'sent'
);

-- Eye tracking calibration profiles
CREATE TABLE IF NOT EXISTS eye_calibration (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    profile_name TEXT DEFAULT 'default',
    screen_center_x REAL,
    screen_center_y REAL,
    tolerance_x REAL,
    tolerance_y REAL,
    calibrated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Active session tracking (for daemon)
CREATE TABLE IF NOT EXISTS active_session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    session_id INTEGER REFERENCES sessions(id),
    started_at TIMESTAMP,
    timer_end_at TIMESTAMP,
    penalty_seconds INTEGER DEFAULT 0
);

-- Part study statistics (for tracking document parts)
CREATE TABLE IF NOT EXISTS part_study_stats (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    card_id INTEGER REFERENCES cards(id) ON DELETE CASCADE,
    part_index INTEGER NOT NULL,
    total_parts INTEGER NOT NULL,
    times_studied INTEGER DEFAULT 0,
    last_score REAL,
    average_score REAL,
    highest_score REAL,
    last_studied_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(card_id, part_index, total_parts)
);

-- Habits/Daily Missions
CREATE TABLE IF NOT EXISTS habits (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    description TEXT,
    icon TEXT,
    target_value INTEGER DEFAULT 1,
    current_value INTEGER DEFAULT 0,
    xp_reward INTEGER DEFAULT 50,
    is_automated BOOLEAN DEFAULT FALSE,
    action_type TEXT, -- 'focus_session', 'review_cards', 'peak_focus', 'manual'
    completed BOOLEAN DEFAULT FALSE,
    last_reset DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Seed default missions
DELETE FROM habits;
INSERT INTO habits (name, description, icon, target_value, xp_reward, is_automated, action_type)
VALUES
('DEEP_WORK_INITIATIVE', 'Complete a focus session of at least 30 minutes.', 'shield', 30, 100, 1, 'focus_session_time'),
('COGNITIVE_REINFORCEMENT', 'Complete a full card review session.', 'psychology', 1, 75, 1, 'review_cards'),
('PEAK_PERFORMANCE', 'Achieve >90% focus in a study/recall session.', 'bolt', 1, 150, 1, 'peak_focus');

-- Create global streak if not exists
INSERT OR IGNORE INTO streaks (id, subject_id, current_streak, longest_streak, total_xp, daily_xp, daily_xp_goal, level)
VALUES (1, NULL, 0, 0, 0, 0, 100, 1);
