from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration


def upgrade(connection: sqlite3.Connection) -> None:
    connection.execute(
        """
        CREATE TABLE heaven_readings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
            mode TEXT NOT NULL CHECK (mode IN ('trend', 'fortune', 'heart')),
            reading_date TEXT NOT NULL,
            subject_key TEXT NOT NULL DEFAULT '',
            result_json TEXT NOT NULL,
            interpretation TEXT NOT NULL DEFAULT '',
            interpretation_status TEXT NOT NULL DEFAULT 'pending' CHECK (
                interpretation_status IN ('pending', 'complete', 'stopped', 'error')
            ),
            request_id TEXT REFERENCES llm_requests(id) ON DELETE SET NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
        """
    )
    connection.execute(
        """
        CREATE INDEX heaven_readings_scope_idx
        ON heaven_readings(user_id, mode, reading_date, id)
        """
    )
    connection.execute(
        """
        CREATE UNIQUE INDEX heaven_fortune_daily_idx
        ON heaven_readings(user_id, reading_date)
        WHERE mode = 'fortune'
        """
    )


def downgrade(connection: sqlite3.Connection) -> None:
    connection.execute("DROP TABLE heaven_readings")


MIGRATION = Migration(
    version=9,
    name="create_heaven_readings",
    signature="heaven:v2:account-readings-unique-daily-fortune",
    upgrade=upgrade,
    downgrade=downgrade,
)
