"""对冲计划期权腿盈亏与交易所对齐."""
from __future__ import annotations

import sqlite3
import unittest

from lib.hedge_plan.hedge_plan_db import get_plan, init_hedge_plan_tables, insert_leg, insert_plan
from lib.hedge_plan.hedge_plan_settle_lib import (
    _parse_opened_ms,
    backfill_hedge_option_legs_realized_pnl,
    resolve_option_leg_realized_pnl,
)


class HedgeExchangePnlTest(unittest.TestCase):
    def test_resolve_prefers_exchange(self):
        leg = {
            "inst_id": "ETH-USD_UM-260719-1850-P",
            "opened_at": "2026-07-17 06:59:18",
            "premium": 5.0,
        }
        hist = [
            {
                "instId": "ETH-USD_UM-260719-1850-P",
                "uTime": "1784400000000",
                "realizedPnl": "12.00",
                "closeAvgPx": "30",
            }
        ]
        pnl, src = resolve_option_leg_realized_pnl(
            leg=leg, hist_rows=hist, fallback=-5.0
        )
        self.assertEqual(src, "exchange")
        self.assertEqual(pnl, 12.0)

    def test_opened_at_beijing_wall_clock_not_utc(self):
        # 北京 09:19 开仓 → UTC 01:19; 到期结算北京 16:00:31 = UTC 08:00:31
        open_ms = _parse_opened_ms("2026-07-20 09:19:30")
        self.assertEqual(open_ms, 1784510370000)
        leg = {
            "inst_id": "ETH-USD_UM-260720-1870-C",
            "opened_at": "2026-07-20 09:19:30",
            "premium": 6.9,
        }
        hist = [
            {
                "instId": "ETH-USD_UM-260720-1870-C",
                "uTime": "1784534431512",
                "realizedPnl": "-7.1812815",
                "pnl": "-6.9",
                "type": "2",
            }
        ]
        pnl, src = resolve_option_leg_realized_pnl(
            leg=leg, hist_rows=hist, fallback=-6.9
        )
        self.assertEqual(src, "exchange")
        self.assertAlmostEqual(pnl, -7.1813, places=4)

    def test_backfill_updates_plan_total(self):
        conn = sqlite3.connect(":memory:")
        conn.row_factory = sqlite3.Row
        init_hedge_plan_tables(conn)
        pid = insert_plan(
            conn,
            {
                "plan_type": "options_options",
                "status": "closed",
                "underlying": "ETH",
                "premium_total": 10,
                "realized_pnl_options": 6.08,
                "realized_pnl_total": 6.08,
                "opened_at": "2026-07-17 06:59:18",
                "closed_at": "2026-07-19 16:00:13",
            },
        )
        insert_leg(
            conn,
            {
                "plan_id": pid,
                "leg_role": "option_a",
                "inst_id": "ETH-USD_UM-260719-1890-C",
                "opt_type": "C",
                "strike": 1890,
                "size": 10,
                "premium": 5.92,
                "status": "closed",
                "realized_pnl": -5.92,
                "opened_at": "2026-07-17 06:59:18",
                "closed_at": "2026-07-19 16:00:13",
            },
        )
        insert_leg(
            conn,
            {
                "plan_id": pid,
                "leg_role": "option_b",
                "inst_id": "ETH-USD_UM-260719-1850-P",
                "opt_type": "P",
                "strike": 1850,
                "size": 10,
                "premium": 4.0,
                "status": "closed",
                "realized_pnl": 12.0,
                "opened_at": "2026-07-17 06:59:18",
                "closed_at": "2026-07-19 08:00:00",
            },
        )
        hist = [
            {
                "instId": "ETH-USD_UM-260719-1890-C",
                "uTime": "1784476813000",
                "realizedPnl": "-5.50",
            },
            {
                "instId": "ETH-USD_UM-260719-1850-P",
                "uTime": "1784448000000",
                "realizedPnl": "11.80",
            },
        ]
        out = backfill_hedge_option_legs_realized_pnl(conn, hist)
        self.assertEqual(out["legs"], 2)
        self.assertEqual(out["plans"], 1)
        plan = get_plan(conn, pid)
        self.assertAlmostEqual(float(plan["realized_pnl_options"]), 6.3, places=4)
        self.assertAlmostEqual(float(plan["realized_pnl_total"]), 6.3, places=4)


if __name__ == "__main__":
    unittest.main()
