"""验证中控 embed-auth 与 login 返回 session_token."""
from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "manual_trading_hub"))
sys.path.insert(0, str(ROOT))

from fastapi.testclient import TestClient

import os

os.environ.setdefault("HUB_PASSWORD", "test-pass")
os.environ.setdefault("HUB_USERNAME", "admin")
os.environ["HUB_ALLOW_PUBLIC"] = "true"

import hub as hub_mod  # noqa: E402

client = TestClient(hub_mod.app)


def main() -> int:
    r = client.post("/api/auth/login", json={"username": "admin", "password": "test-pass"})
    assert r.status_code == 200, r.text
    data = r.json()
    assert data.get("ok") is True, data
    token = data.get("session_token")
    assert token, "login 应返回 session_token"

    r2 = client.get(f"/embed-auth?token={token}&next=/monitor", follow_redirects=False)
    assert r2.status_code in (302, 307), r2.status_code
    assert r2.headers.get("location", "").endswith("/monitor")
    assert hub_mod.SESSION_COOKIE in r2.headers.get("set-cookie", "")

    r3 = client.get("/monitor", cookies={hub_mod.SESSION_COOKIE: token})
    assert r3.status_code == 200, r3.status_code

    csp = client.get("/login").headers.get("content-security-policy", "")
    assert "frame-ancestors" in csp, csp

    print("OK: embed-auth sets session cookie; login returns session_token")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
