"""Unit tests for ORB state trigger_type persistence."""
from __future__ import annotations

import sqlite3

from apps.orb_trader.models import ORBPositionRow, ORBTradeRow
from apps.orb_trader.state import ORBStateManager


def test_position_and_trade_trigger_type_persist(tmp_path):
    state = ORBStateManager(str(tmp_path / "orb.db"))
    session_id = state.create_session("test", "config.yaml", 10_000.0)

    pos = ORBPositionRow(
        session_id=session_id,
        date="2026-01-05",
        ticker="BURST",
        direction="long",
        entry_price=100.0,
        entry_time="2026-01-05T09:40:00-05:00",
        shares=10,
        orb_high=105.0,
        orb_low=99.0,
        atr_at_entry=2.0,
        stop_distance=1.5,
        current_stop=98.5,
        peak_price=100.0,
        trigger_type="market_thrust_opening_burst",
    )
    state.save_position(pos)

    saved_pos = state.get_open_positions(session_id, "2026-01-05")[0]
    assert saved_pos.trigger_type == "market_thrust_opening_burst"

    trade = ORBTradeRow(
        trade_id="trade-1",
        session_id=session_id,
        date="2026-01-05",
        ticker="BURST",
        direction="long",
        entry_price=100.0,
        exit_price=103.0,
        entry_time="2026-01-05T09:40:00-05:00",
        exit_time="2026-01-05T15:55:00-05:00",
        shares=10,
        pnl=30.0,
        r_multiple=2.0,
        exit_reason="close",
        trigger_type="market_thrust_opening_burst",
    )
    state.save_trade(trade)

    saved_trade = state.list_trades(session_id)[0]
    assert saved_trade["trigger_type"] == "market_thrust_opening_burst"


def test_existing_db_is_migrated_with_orb_trigger_default(tmp_path):
    db_path = tmp_path / "old_orb.db"
    with sqlite3.connect(db_path) as conn:
        conn.executescript(
            """
            CREATE TABLE sessions (
                session_id TEXT PRIMARY KEY,
                session_name TEXT NOT NULL UNIQUE,
                config_path TEXT NOT NULL,
                initial_equity REAL NOT NULL,
                created_at TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'active'
            );
            CREATE TABLE orb_positions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                date TEXT NOT NULL,
                ticker TEXT NOT NULL,
                direction TEXT NOT NULL,
                entry_price REAL NOT NULL,
                entry_time TEXT NOT NULL,
                shares INTEGER NOT NULL,
                orb_high REAL NOT NULL,
                orb_low REAL NOT NULL,
                atr_at_entry REAL NOT NULL,
                stop_distance REAL NOT NULL,
                current_stop REAL NOT NULL,
                peak_price REAL NOT NULL,
                trailing_active INTEGER NOT NULL DEFAULT 0,
                rvol REAL,
                composite_score REAL,
                order_id TEXT,
                status TEXT NOT NULL DEFAULT 'open',
                UNIQUE(session_id, date, ticker)
            );
            CREATE TABLE trades (
                trade_id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL,
                date TEXT NOT NULL,
                ticker TEXT NOT NULL,
                direction TEXT NOT NULL,
                entry_price REAL NOT NULL,
                exit_price REAL NOT NULL,
                entry_time TEXT NOT NULL,
                exit_time TEXT NOT NULL,
                shares INTEGER NOT NULL,
                pnl REAL NOT NULL,
                r_multiple REAL NOT NULL,
                exit_reason TEXT NOT NULL,
                atr_at_entry REAL,
                rvol REAL,
                composite_score REAL
            );
            CREATE TABLE daily_snapshots (
                session_id TEXT NOT NULL,
                date TEXT NOT NULL,
                equity REAL NOT NULL,
                daily_pnl REAL,
                total_pnl REAL,
                trades_taken INTEGER,
                stops_hit INTEGER,
                drawdown_pct REAL,
                PRIMARY KEY (session_id, date)
            );
            CREATE TABLE daily_state (
                session_id TEXT NOT NULL,
                date TEXT NOT NULL,
                cumulative_loss REAL NOT NULL DEFAULT 0.0,
                stops_hit INTEGER NOT NULL DEFAULT 0,
                kill_switch INTEGER NOT NULL DEFAULT 0,
                phase TEXT NOT NULL DEFAULT 'idle',
                PRIMARY KEY (session_id, date)
            );
            CREATE TABLE orb_candidates (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                date TEXT NOT NULL,
                ticker TEXT NOT NULL,
                direction TEXT NOT NULL,
                orb_high REAL NOT NULL,
                orb_low REAL NOT NULL,
                breakout_level REAL NOT NULL,
                atr REAL NOT NULL,
                rvol REAL NOT NULL,
                gap_pct REAL NOT NULL,
                composite_score REAL NOT NULL,
                status TEXT NOT NULL DEFAULT 'pending',
                UNIQUE(session_id, date, ticker)
            );
            """
        )

    ORBStateManager(str(db_path))

    with sqlite3.connect(db_path) as conn:
        position_columns = {
            row[1] for row in conn.execute("PRAGMA table_info(orb_positions)")
        }
        trade_columns = {row[1] for row in conn.execute("PRAGMA table_info(trades)")}
    assert "trigger_type" in position_columns
    assert "trigger_type" in trade_columns
