"""Security-lake playbook, step 1: land an OCSF lake in the customer's bucket.

The lake comes from the seeded `ocsf_lake` generator of tessera-testing
(routine users, shift workers and a few account takeovers whose tell is the
order of their steps), written as the three OCSF classes the `ocsf` pack reads.
On your own lake skip this step: point step 3 at the bucket your OCSF export
already writes.

On the local stack the bucket is a fake customer bucket, written through the
stack's control origin. Against a real deployment, upload the same objects to
your bucket with your own tooling.
"""

import base64
import json
import os
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path

import httpx

from tessera_testing.domainpacks.ocsf_lake import OCSF_LAKE_FILES, ocsf_lake_tables
from tessera_testing.generators import generate
from tessera_testing.scenarios import PresenceRates

STATE = Path(os.environ.get("TESSERA_STATE_DIR", "."))
CONTROL = os.environ["TESSERA_CONTROL_BASE"]  # the local stack's control origin
BUCKET = "acme-security-lake"
START = datetime(2026, 7, 1, tzinfo=UTC)
DAYS = 14

scenario = generate(
    "ocsf_lake",
    entities=400,
    seed=11,
    start=START,
    days=DAYS,
    presence_rates=PresenceRates(missing=0.0, sentinel=0.0, corrupted=0.0),
)
tables = ocsf_lake_tables(scenario.events)
objects = [
    {
        "provider": "gcs",
        "bucket": BUCKET,
        "name": f"ocsf/{catalog.removeprefix('ocsf.')}/{OCSF_LAKE_FILES[catalog]}",
        "content_b64": base64.b64encode(data).decode("ascii"),
    }
    for catalog, data in sorted(tables.items())
]
response = httpx.post(f"{CONTROL}/customer-objects", json={"objects": objects}, timeout=120.0)
response.raise_for_status()

counts = Counter(event.event_type for event in scenario.events)
archetypes = Counter(entity["archetype"] for entity in scenario.ground_truth["entities"].values())
print(f"objects written: {response.json()['written']}")
for event_type in sorted(counts):
    print(f"  {event_type}: {counts[event_type]} events")
print("users by archetype:", json.dumps(dict(sorted(archetypes.items()))))

# The ground truth stays with the fixture: step 9 uses it to disposition alerts
# the way an analyst who knew the answer would.
takeovers = sorted(
    user
    for user, entity in scenario.ground_truth["entities"].items()
    if entity["archetype"] == "takeover"
)
(STATE / "security-lake.json").write_text(
    json.dumps(
        {
            "bucket": BUCKET,
            "window": {"start": START.isoformat(), "days": DAYS},
            "takeovers": takeovers,
            "users": len(scenario.ground_truth["entities"]),
        }
    )
)
