"""期权平仓门控:可回收≥2×权利金且持续持有."""
from __future__ import annotations

import unittest

from lib.options.options_close_gate_lib import (
    clear_close_gate,
    is_close_gate_passed,
    mark_close_gate_passed,
    update_close_gate,
)


class OptionsCloseGateTests(unittest.TestCase):
    def setUp(self):
        clear_close_gate()

    def tearDown(self):
        clear_close_gate()

    def test_below_2x_not_ready(self):
        g = update_close_gate("ETH-X", recycle_usdc=15.0, premium_paid=10.0, now=1000.0)
        self.assertFalse(g["recycle_ok"])
        self.assertFalse(g["ready"])

    def test_meets_2x_needs_hold(self):
        g1 = update_close_gate("ETH-X", recycle_usdc=20.0, premium_paid=10.0, now=1000.0)
        self.assertTrue(g1["recycle_ok"])
        self.assertFalse(g1["ready"])
        self.assertAlmostEqual(g1["remain_seconds"], 120.0)

        g2 = update_close_gate("ETH-X", recycle_usdc=21.0, premium_paid=10.0, now=1120.0)
        self.assertTrue(g2["ready"])
        self.assertGreaterEqual(g2["held_seconds"], 120.0)

    def test_break_resets_timer(self):
        update_close_gate("ETH-X", recycle_usdc=20.0, premium_paid=10.0, now=1000.0)
        update_close_gate("ETH-X", recycle_usdc=21.0, premium_paid=10.0, now=1100.0)
        g_break = update_close_gate("ETH-X", recycle_usdc=12.0, premium_paid=10.0, now=1110.0)
        self.assertFalse(g_break["recycle_ok"])
        g_again = update_close_gate("ETH-X", recycle_usdc=22.0, premium_paid=10.0, now=1111.0)
        self.assertTrue(g_again["recycle_ok"])
        self.assertFalse(g_again["ready"])
        self.assertAlmostEqual(g_again["held_seconds"], 0.0)

    def test_passed_latches_after_ready(self):
        update_close_gate("ETH-Y", recycle_usdc=20.0, premium_paid=10.0, now=1000.0)
        g_ready = update_close_gate("ETH-Y", recycle_usdc=21.0, premium_paid=10.0, now=1120.0)
        self.assertTrue(g_ready["ready"])
        self.assertTrue(g_ready["passed"])
        self.assertTrue(is_close_gate_passed("ETH-Y"))
        # 后续回收跌破 2×:计时重置,但 passed 仍保留供续批只验流动性
        g_drop = update_close_gate("ETH-Y", recycle_usdc=5.0, premium_paid=10.0, now=1130.0)
        self.assertFalse(g_drop["recycle_ok"])
        self.assertTrue(g_drop["passed"])
        self.assertFalse(g_drop["auto_close_blocked"])

    def test_mark_passed_manual(self):
        mark_close_gate_passed("ETH-Z")
        self.assertTrue(is_close_gate_passed("ETH-Z"))


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