import base64, hashlib, json, os, time, uuid
from pathlib import Path
import httpx

BASE = "https://egoview.alpen-y.top/api/v1"
TOKEN = os.environ["EGOVIEW_TOKEN"]
VIDEO = Path("rgb.mp4")
CALIBRATION = os.getenv("EGOVIEW_CALIBRATION")
PROJECTION = "pinhole"  # pinhole / rectified / fisheye
LAYOUT = "mono"        # mono / sbs_left

def key():
    return uuid.uuid4().hex

def call(client, method, path, **kwargs):
    response = client.request(method, BASE + path, **kwargs)
    response.raise_for_status()
    return response.json()

# Hash in chunks so long videos do not need to fit in memory.
sha, md5 = hashlib.sha256(), hashlib.md5()
with VIDEO.open("rb") as source:
    for chunk in iter(lambda: source.read(1024 * 1024), b""):
        sha.update(chunk)
        md5.update(chunk)

# Separate clients: send Bearer credentials only to the API, never to storage.
with httpx.Client(headers={"Authorization": "Bearer " + TOKEN}, timeout=60) as api, \
     httpx.Client(timeout=httpx.Timeout(120, connect=15)) as storage:
    metadata = {
        "filename": VIDEO.name, "size": VIDEO.stat().st_size,
        "sha256": sha.hexdigest(),
        "content_md5": base64.b64encode(md5.digest()).decode(),
        "input_projection": PROJECTION, "input_layout": LAYOUT,
    }
    if CALIBRATION:
        calibration = call(api, "POST", "/calibrations/normalize", json={
            "calibration": json.loads(Path(CALIBRATION).read_text(encoding="utf-8-sig"))
        })["calibration"]
        if "D" in calibration or "schema" in calibration:
            metadata["camera_calibration"] = calibration
        else:
            metadata["camera_K"] = calibration["K"]
    upload_key, run_key = key(), key()
    # Retain these keys. Reuse the same key and body when retrying a timed-out request.
    Path("request-keys.json").write_text(json.dumps({
        "upload_key": upload_key, "run_key": run_key
    }))
    intent = call(api, "POST", "/uploads", json=metadata,
                  headers={"Idempotency-Key": upload_key})
    upload_id = intent["upload_id"]
    Path("upload-id.txt").write_text(upload_id)
    with VIDEO.open("rb") as source:
        response = storage.put(intent["upload_url"],
                               headers=intent["upload_headers"], content=source)
        response.raise_for_status()
    session = call(api, "POST", f"/uploads/{upload_id}/complete")
    run = call(api, "POST", "/runs", json={
        "session_id": session["session_id"], "pipeline": "refine-v10", "params": {}
    }, headers={"Idempotency-Key": run_key})
    run_id = run["run_id"]
    Path("run-id.txt").write_text(run_id)
    print("run_id:", run_id)
    deadline = time.monotonic() + 3600
    while not run["terminal"]:
        if time.monotonic() > deadline:
            raise TimeoutError(f"Stopped waiting locally; the remote run continues: {run_id}")
        time.sleep(5)
        run = call(api, "GET", f"/runs/{run_id}")
        print(run["state"], run.get("waiting_reason") or "")
    if run["state"] != "succeeded":
        raise RuntimeError(run.get("error") or run["state"])
    manifest = call(api, "GET", f"/runs/{run_id}/artifacts")
    output = Path("outputs").resolve()
    output.mkdir(exist_ok=True)
    for artifact in manifest["artifacts"]:
        name = artifact["name"]
        target = (output / name).resolve()
        if output not in target.parents:
            raise ValueError("Invalid artifact path")
        signed = call(api, "POST", f"/runs/{run_id}/artifacts/"
                      + artifact["artifact_id"] + "/download", json={})
        target.parent.mkdir(parents=True, exist_ok=True)
        temporary = target.with_name(target.name + ".part")
        digest, size = hashlib.sha256(), 0
        with storage.stream("GET", signed["url"]) as response:
            response.raise_for_status()
            with temporary.open("wb") as destination:
                for chunk in response.iter_bytes(1024 * 1024):
                    destination.write(chunk)
                    digest.update(chunk)
                    size += len(chunk)
        if size != artifact["bytes"] or (artifact["sha256"] and
                digest.hexdigest() != artifact["sha256"]):
            temporary.unlink(missing_ok=True)
            raise ValueError("Download verification failed: " + name)
        temporary.replace(target)
        print("Saved:", name)
