import requests
from pathlib import Path
from datetime import datetime

BASE_URL = "http://thinkcentre.local:8444"

def snapshot_all_hires(out_dir: str = "."):
    out = Path(out_dir)
    out.mkdir(exist_ok=True)

    cameras = requests.get(f"{BASE_URL}/api/cameras", timeout=5).json()["cameras"]

    results = {}
    errors = {}
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")

    for cam in cameras:
        cam_id = cam["id"]
        url = f"{BASE_URL}/api/snapshot/{cam_id}/hires"

        try:
            resp = requests.get(url, timeout=20)
            if not resp.ok:
                reason = resp.json().get("error", resp.text) if resp.content else resp.reason
                print(f"{cam_id} ({cam['name']}): FEHLER {resp.status_code} – {reason}")
                errors[cam_id] = reason
                continue

            filename = out / f"{ts}_{cam_id}_{cam['position']}.jpg"
            filename.write_bytes(resp.content)
            w = resp.headers.get("X-Frame-Width", "?")
            print(f"{cam_id} ({cam['name']}): {len(resp.content)//1024} kB, {w}px → {filename.name}")
            results[cam_id] = str(filename)

        except requests.exceptions.Timeout:
            print(f"{cam_id} ({cam['name']}): TIMEOUT (>20s)")
            errors[cam_id] = "timeout"
        except Exception as e:
            print(f"{cam_id} ({cam['name']}): EXCEPTION – {e}")
            errors[cam_id] = str(e)

    return results, errors

if __name__ == "__main__":
    files, errs = snapshot_all_hires("./files")
    print("\nErfolg:", files)
    if errs:
        print("Fehler:", errs)