"""Security-lake playbook, step 10: write scores, bands and evidence back to Snowflake.

A Snowflake credential is a source with key-pair setup (Tessera mints the key;
you run the printed `ALTER USER` once). The export schedule is the production
shape, daily after the scoring refresh; this page then runs the same export
once, now. On the local stack Snowflake is a twin, read through the control
origin.
"""

import os
import sys
from pathlib import Path

import httpx

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))  # playbooks/playbook_api.py
from playbook_api import Api, State

api, state = Api(), State("security-lake")

credential = api.post(
    "/sources",
    {
        "name": "snowflake write-back",
        "kind": "snowflake",
        "config": {
            "account": "acme-security",
            "warehouse": "TESSERA_WH",
            "database": "LAKE",
            "schema": "TESSERA",
            "table": "USER_SCORES",
        },
        "credentials": {"username": "TESSERA_WRITER"},
    },
    key="security-lake-snowflake",
)
print(f"snowflake key-pair setup issued: {bool((credential.get('setup') or {}).get('public_key'))}")
destination = {
    "kind": "snowflake",
    "credential_id": credential["source_id"],
    "database": "LAKE",
    "schema": "TESSERA",
    "table": "USER_SCORES",
}
schedule = api.post(
    "/slots/security/export-schedules",
    {
        "cadence": {"kind": "daily", "at_utc": "04:00"},
        "export": {"destination": destination, "mode": "append", "refresh_first": True},
    },
    key="security-lake-export-schedule",
)
print(f"export schedule: daily at 04:00 UTC, status: {schedule.get('status')}")
export = api.post(
    "/slots/security/warehouse-exports",
    {"destination": destination, "mode": "append", "include": ["scores", "evidence"]},
    key="security-lake-export",
)
export = api.wait(
    f"/slots/security/warehouse-exports/{export['export_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the Snowflake export",
)
print(f"export: {export['status']}, mode: {export.get('mode')}")
tables = httpx.get(f"{os.environ['TESSERA_CONTROL_BASE']}/fakes/snowflake", timeout=30.0).json()
rows = {table["name"]: table["rows"] for table in tables.get("tables") or []}
landed = rows.get("LAKE.TESSERA.USER_SCORES")
exported = int(export.get("rows_exported") or 0)
print(f"rows exported: {exported > 0}")
print(f"snowflake LAKE.TESSERA.USER_SCORES rows match the export: {landed == exported}")
if exported <= 0 or landed != exported:
    sys.exit(f"the write-back is empty or incomplete: exported {exported}, landed {landed}")
