"""期权模块 SQLite 表."""
from __future__ import annotations

import sqlite3


def init_options_tables(conn: sqlite3.Connection) -> None:
    from lib.options.options_review_db import init_options_review_tables

    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS options_trades (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            inst_id TEXT NOT NULL,
            underlying TEXT NOT NULL,
            opt_type TEXT NOT NULL,
            strike REAL,
            exp_time TEXT,
            sheets INTEGER NOT NULL,
            eth_amount REAL NOT NULL,
            open_quote REAL,
            premium_paid REAL,
            status TEXT DEFAULT 'open',
            close_quote REAL,
            premium_received REAL,
            realized_pnl REAL,
            profit_alert_sent INTEGER DEFAULT 0,
            signal_note TEXT,
            exchange_ord_id TEXT,
            close_ord_id TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            closed_at TIMESTAMP
        )
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS options_convert_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            from_ccy TEXT,
            to_ccy TEXT,
            rfq_sz REAL,
            received_sz REAL,
            quote_id TEXT,
            status TEXT,
            message TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS options_history_hidden (
            history_key TEXT PRIMARY KEY,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS options_transfer_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ccy TEXT,
            amount REAL,
            from_account TEXT,
            to_account TEXT,
            status TEXT,
            message TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS options_target_monitors (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            inst_id TEXT NOT NULL,
            underlying TEXT,
            opt_type TEXT,
            target_index REAL NOT NULL,
            trade_id INTEGER,
            sheets INTEGER,
            status TEXT DEFAULT 'active',
            trigger_idx REAL,
            close_ord_id TEXT,
            message TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            triggered_at TIMESTAMP
        )
        """
    )
    conn.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_options_target_monitors_status
        ON options_target_monitors(status)
        """
    )
    init_options_review_tables(conn)


def sum_open_premium_paid(conn: sqlite3.Connection, inst_id: str) -> float | None:
    """同合约所有 open 腿权利金合计(加仓后显示/门控用)."""
    inst = (inst_id or "").strip()
    if not inst:
        return None
    row = conn.execute(
        """
        SELECT SUM(premium_paid) AS total, COUNT(*) AS n
        FROM options_trades
        WHERE inst_id = ? AND status = 'open' AND premium_paid IS NOT NULL
        """,
        (inst,),
    ).fetchone()
    if not row or int(row["n"] or 0) < 1:
        return None
    return round(float(row["total"] or 0), 4)


def sum_open_sheets(conn: sqlite3.Connection, inst_id: str) -> int | None:
    """同合约所有 open 腿张数合计."""
    inst = (inst_id or "").strip()
    if not inst:
        return None
    row = conn.execute(
        """
        SELECT SUM(sheets) AS total, COUNT(*) AS n
        FROM options_trades
        WHERE inst_id = ? AND status = 'open'
        """,
        (inst,),
    ).fetchone()
    if not row or int(row["n"] or 0) < 1:
        return None
    return int(row["total"] or 0)
