"""PostHog-loop playbook, step 1: land the product's events.

The events are the quickstart's sample dataset (generated e-commerce orders
and their repeat-purchase outcomes; checksums verified from its manifest). On
your own product, the PostHog or HTTP connector sends these; here the orders
file is uploaded, mapped with the quickstart's mapping and synced.
"""

import hashlib
import io
import json
import os
import sys
import zipfile
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("posthog-loop")

SAMPLE_URL = os.environ.get(
    "TESSERA_SAMPLE_URL", "https://docs.staging.tessera.zone/downloads/tessera-sample-v1.zip"
)
archive = zipfile.ZipFile(io.BytesIO(httpx.get(SAMPLE_URL, timeout=120.0).content))
manifest = json.loads(archive.read("manifest.json"))
for name, meta in manifest["files"].items():
    assert hashlib.sha256(archive.read(name)).hexdigest() == meta["sha256"], name
print("sample dataset verified")
sample_dir = state.path.parent / "posthog-loop-sample"
archive.extractall(sample_dir)

session = api.post(
    "/uploads", {"filename": "ecommerce_orders.csv", "format": "csv"}, key="posthog-loop-orders"
)
orders = (sample_dir / "ecommerce_orders.csv").read_bytes()
httpx.put(session["upload_url"], content=orders, timeout=120.0).raise_for_status()
api.post(f"/uploads/{session['upload_id']}:complete")
upload = api.get(f"/uploads/{session['upload_id']}")
api.wait(
    f"/syncs/{upload['sync_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the landing sync",
    polls=150,
)
mapping_path = Path(__file__).resolve().parents[2] / "quickstart" / "mapping-orders.json"
api.put(f"/sources/{upload['source_id']}/mapping", json.loads(mapping_path.read_text()))
sync = api.post(
    f"/sources/{upload['source_id']}/syncs", {"mode": "full"}, key="posthog-loop-orders-sync"
)
sync = api.wait(
    f"/syncs/{sync['sync_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the orders sync",
    polls=150,
)
print(f"orders sync: {sync['status']}, rows_rejected: {sync.get('rows_rejected')}")
state.update(
    sample_dir=str(sample_dir),
    start="2025-01-01T00:00:00Z",
    end="2025-07-01T00:00:00Z",
)
