"""Security-lake playbook, step 4: run each source's sync now.

`POST /sources/{source_id}/syncs` is the manual trigger; the schedule's tick
starts the same sync. Every row the catalog maps lands as an event.
"""

import sys
from pathlib import Path

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")

for catalog, source_id in sorted(state["sources"].items()):
    folder = catalog.removeprefix("ocsf.")
    sync = api.post(
        f"/sources/{source_id}/syncs", {"mode": "full"}, key=f"security-lake-sync-{folder}"
    )
    done = api.wait(
        f"/syncs/{sync['sync_id']}",
        lambda job: job.get("status") in ("succeeded", "failed"),
        what=f"the {catalog} sync",
    )
    landed = done.get("events_normalized")
    print(f"{catalog}: {done['status']}, rows_rejected: {done.get('rows_rejected')}")
    print(f"{catalog}: events landed: {landed}")
    if done["status"] != "succeeded" or done.get("rows_rejected") or not landed:
        sys.exit(f"{catalog} did not land cleanly: {done}")
