"""Quickstart step 6 (planned Python SDK) — train and follow the run to evaluation.

The normal invocation is one line:
    client.api.create_run(models.TrainingRunRequest(dataset_id=..., model_config_tier="S"))
This executable copy layers on ci-train-profile.json — the documented CI
override profile (reduced dims, <= 50 steps, CPU) — so the docs pipeline
really trains this model on every change.
"""

import json
import os
import time
from pathlib import Path

from tessera import Tessera
from tessera._generated import models

client = Tessera(base_url=os.environ["TESSERA_API_BASE"])
state_dir = Path(os.environ.get("TESSERA_STATE_DIR", "."))
dataset_id = (state_dir / "dataset_id").read_text().strip()

profile = json.loads(Path("../quickstart/ci-train-profile.json").read_text())
profile.pop("_comment", None)
run = client.api.create_run(models.TrainingRunRequest(dataset_id=dataset_id, **profile))
print(f"run started: tier={profile['model_config_tier']}")

for _ in range(600):
    run = client.api.get_run(run.run_id)
    if run.status.value in ("succeeded", "failed", "cancelled"):
        break
    time.sleep(2)
print(f"run: {run.status.value} total_steps={run.total_steps}")

model_id = str(run.model_id)
for _ in range(600):
    model = client.api.get_model(model_id)
    if model.status.value in ("evaluated", "promoted", "archived"):
        break
    time.sleep(2)
print(f"model: {model.status.value}")

report = client.api.get_model_eval_report(model_id)
for gate in sorted(report.gates.keys()):
    print(f"gate {gate}: {report.gates[gate]['status']}")

(state_dir / "model_id").write_text(model_id)
client.close()
