import datetime as dt
import pytest
from fastapi.testclient import TestClient


def test_current_session_windows():
    from app.trade_alerts import current_session
    d = dt.date(2026, 7, 2)
    assert current_session(dt.datetime.combine(d, dt.time(8, 40))) == "pre"
    assert current_session(dt.datetime.combine(d, dt.time(10, 0))) == "regular"
    assert current_session(dt.datetime.combine(d, dt.time(17, 0))) == "after"
    assert current_session(dt.datetime.combine(d, dt.time(20, 0))) == "closed"


@pytest.fixture
def client(monkeypatch, tmp_path):
    from app import db as _db
    monkeypatch.setattr(_db, "DB_PATH", str(tmp_path / "stock.db"))
    _db.init_db()
    monkeypatch.setenv("WEBAI_API_KEY", "k")
    from app.main import app
    return TestClient(app)


def test_monitor_set_requires_auth(client):
    assert client.get("/api/webai/trade-alert/monitor-set").status_code == 401


def test_monitor_set_ok(client):
    r = client.get("/api/webai/trade-alert/monitor-set", headers={"X-WebAI-Key": "k"})
    assert r.status_code == 200
    body = r.json()
    assert body["session"] in ("pre", "regular", "after", "closed")
    assert "buy_targets" in body and "sell_targets" in body
    assert body["exit_params"]["trailing_pct"] == 0.10


def test_monitor_set_exit_params_include_climax(client):
    """climax 파라미터 중앙화 — 워커가 하드코딩 대신 NAS exit_params에서 받아 튜닝."""
    ep = client.get("/api/webai/trade-alert/monitor-set",
                    headers={"X-WebAI-Key": "k"}).json()["exit_params"]
    assert ep["climax_vol_x"] == 3.0
    assert ep["climax_close_pct"] == 0.97
