"""单独期权翻倍出场命中条件."""
from __future__ import annotations

import sqlite3
import tempfile
import unittest
from pathlib import Path

from lib.options.options_db import init_options_tables
from lib.options.options_profit_exit_lib import (
    normalize_profit_exit_mult,
    profit_exit_by_inst,
    profit_exit_hit,
    required_recycle_usdc,
    set_profit_exit,
)


class TestOptionsProfitExit(unittest.TestCase):
    def test_hit_one_x_means_profit_equals_premium(self):
        # 1倍:盈利=权利金 ⇒ 回收≥2×权利金
        self.assertTrue(profit_exit_hit(premium_paid=10.0, recycle_usdc=20.0, mult=1.0))
        self.assertFalse(profit_exit_hit(premium_paid=10.0, recycle_usdc=19.9, mult=1.0))
        self.assertEqual(required_recycle_usdc(10.0, 1.0), 20.0)

    def test_hit_two_x(self):
        self.assertTrue(profit_exit_hit(premium_paid=10.0, recycle_usdc=30.0, mult=2.0))
        self.assertFalse(profit_exit_hit(premium_paid=10.0, recycle_usdc=29.9, mult=2.0))

    def test_normalize_mult(self):
        self.assertEqual(normalize_profit_exit_mult(None), 1.0)
        self.assertEqual(normalize_profit_exit_mult(0), 1.0)
        self.assertEqual(normalize_profit_exit_mult("1.5"), 1.5)

    def test_set_and_clear(self):
        with tempfile.TemporaryDirectory() as td:
            db = Path(td) / "t.db"
            conn = sqlite3.connect(str(db))
            conn.row_factory = sqlite3.Row
            init_options_tables(conn)
            conn.execute(
                """
                INSERT INTO options_trades
                (inst_id, underlying, opt_type, sheets, eth_amount, premium_paid, status)
                VALUES ('ETH-X', 'ETH', 'C', 1, 0.01, 10.0, 'open')
                """
            )
            conn.commit()
            out = set_profit_exit(conn, inst_id="ETH-X", enabled=True, mult=1.5)
            self.assertTrue(out["ok"])
            conn.commit()
            m = profit_exit_by_inst(conn)
            self.assertTrue(m["ETH-X"]["profit_exit_enabled"])
            self.assertEqual(m["ETH-X"]["profit_exit_mult"], 1.5)
            self.assertEqual(m["ETH-X"]["required_recycle"], 25.0)
            out2 = set_profit_exit(conn, inst_id="ETH-X", enabled=False, mult=1.5)
            self.assertTrue(out2["ok"])
            conn.commit()
            m2 = profit_exit_by_inst(conn)
            self.assertNotIn("ETH-X", m2)
            conn.close()


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