from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration


def upgrade(connection: sqlite3.Connection) -> None:
    connection.execute(
        """
        CREATE TABLE trading_days (
            trade_date TEXT PRIMARY KEY,
            is_open INTEGER NOT NULL CHECK (is_open IN (0, 1)),
            previous_open_date TEXT,
            source TEXT NOT NULL,
            observed_at TEXT NOT NULL
        )
        """
    )
    connection.execute(
        """
        CREATE TABLE market_entities (
            entity_type TEXT NOT NULL,
            identifier TEXT NOT NULL,
            code TEXT NOT NULL,
            name TEXT NOT NULL,
            search_key TEXT NOT NULL,
            sector TEXT,
            active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
            source TEXT NOT NULL,
            observed_at TEXT NOT NULL,
            PRIMARY KEY (entity_type, identifier)
        )
        """
    )
    connection.execute(
        """
        CREATE INDEX market_entities_search_idx
            ON market_entities(active, search_key, entity_type)
        """
    )
    connection.execute(
        """
        INSERT INTO market_entities (
            entity_type, identifier, code, name, search_key,
            sector, active, source, observed_at
        ) VALUES
            (
                'index', '000001.SH', '000001', '上证指数',
                '000001 上证指数 shanghai', NULL, 1, 'local', '2026-07-30T00:00:00+08:00'
            ),
            (
                'index', '399001.SZ', '399001', '深证成指',
                '399001 深证成指 shenzhen', NULL, 1, 'local', '2026-07-30T00:00:00+08:00'
            ),
            (
                'index', '399006.SZ', '399006', '创业板指',
                '399006 创业板指 chinext', NULL, 1, 'local', '2026-07-30T00:00:00+08:00'
            )
        """
    )
    connection.execute(
        """
        CREATE TABLE market_summaries (
            trade_date TEXT PRIMARY KEY,
            observed_at TEXT NOT NULL,
            state TEXT NOT NULL CHECK (state IN ('realtime', 'final', 'archive')),
            source TEXT NOT NULL,
            coverage REAL NOT NULL CHECK (coverage >= 0 AND coverage <= 1),
            payload_json TEXT NOT NULL,
            created_at TEXT NOT NULL
        )
        """
    )
    connection.execute(
        """
        CREATE TABLE chart_series (
            entity_type TEXT NOT NULL,
            identifier TEXT NOT NULL,
            interval TEXT NOT NULL CHECK (interval IN ('day', 'minute')),
            trade_date TEXT NOT NULL,
            observed_at TEXT NOT NULL,
            source TEXT NOT NULL,
            usage TEXT NOT NULL CHECK (usage IN ('display', 'calculation')),
            adjustment TEXT NOT NULL,
            coverage REAL NOT NULL CHECK (coverage >= 0 AND coverage <= 1),
            payload_json TEXT NOT NULL,
            created_at TEXT NOT NULL,
            PRIMARY KEY (entity_type, identifier, interval, trade_date)
        )
        """
    )
    connection.execute(
        """
        CREATE INDEX chart_series_latest_idx
            ON chart_series(entity_type, identifier, interval, trade_date DESC)
        """
    )


def downgrade(connection: sqlite3.Connection) -> None:
    connection.execute("DROP TABLE chart_series")
    connection.execute("DROP TABLE market_summaries")
    connection.execute("DROP TABLE market_entities")
    connection.execute("DROP TABLE trading_days")


MIGRATION = Migration(
    version=3,
    name="create_market_foundation",
    signature="market:v1:calendar-entities-summary-chart-provenance",
    upgrade=upgrade,
    downgrade=downgrade,
)
