#!/usr/bin/env python3
"""Robot loop example: photograph → classify → sort.

Runs against Cikada Vision with the robot's API key and prints one decision
line per garment. Use it as the starting point for the robot controller, or
as a simulator that feeds the capture queue from a folder of photos.

    export CIKADA_API_KEY=ck_live_...
    export CIKADA_ROBOT_ID=<uuid from /robots>          # optional but recommended
    python robot_loop.py --once front.jpg label.jpg     # one garment, several views
    python robot_loop.py --watch ./camera --interval 2  # every new file in a folder
    python robot_loop.py --once front.jpg --async       # queue, then poll for the answer
    python robot_loop.py --once front.jpg --early 6     # send at capture, ask for the bin 6 s later

Exit code 0 when every garment got a decision, 1 otherwise. The last decision
is also printed as JSON on the final line so a controller can parse it.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from cikada_vision import REUNFOLD, TRASH, CikadaVision, CikadaVisionError, Classification, iter_garment_files  # noqa: E402

# Bins come from the server (Settings → Sorting). FALLBACK is used when a garment
# gets no answer at all; it is set to the organization's "unsure" bin at start-up.
FALLBACK = {"bin": "review", "name": "review", "slot": None}
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".heic"}


def reunfold_and_photograph(files):
    """The robot's unfolding sequence. Replace this with the real one: untangle
    the garment again, photograph it and return the new image files. The
    simulator sends the same photos again."""
    return files


def move_to_diverter(seconds: float) -> None:
    """The garment's way from the camera to the diverter. Replace this with the
    real handling; the simulator just waits. Vision reads the photos meanwhile."""
    time.sleep(seconds)


def sort_garment(vision: CikadaVision, files, args) -> dict:
    """One garment: the files are different views of the same item. When Vision
    answers "retry" (a field is below the certainty this robot requires), the
    garment is re-unfolded and photographed again and sent as a retry of the
    previous attempt, until Vision sorts it or the retries are used up."""
    started = time.monotonic()
    retry_of = None
    attempts = []
    for _ in range(11):  # Vision caps retries (at most 10); this only guards the loop.
        images = iter_garment_files(files)
        try:
            if args.early is not None:
                # Photograph early, decide late (D120): the photos go up at capture, the
                # bin is asked for at the diverter; past --decision-wait it is the fallback bin.
                item_id = vision.submit(images, robot_id=args.robot, batch_id=args.batch_id, external_ref=args.external_ref, retry_of=retry_of)
                move_to_diverter(args.early)
                result = vision.decision(item_id, wait=args.decision_wait)
            elif args.use_async:
                item_id = vision.submit(images, robot_id=args.robot, batch_id=args.batch_id, external_ref=args.external_ref, retry_of=retry_of)
                result = vision.wait_for(item_id, timeout=args.timeout)
            else:
                result = vision.classify(images, robot_id=args.robot, batch_id=args.batch_id, external_ref=args.external_ref, retry_of=retry_of)
        except CikadaVisionError as failure:
            # The garment is stored whenever the API accepted the upload; route it to
            # the fallback bin and carry on with the next one.
            elapsed = time.monotonic() - started
            print(f"{'/'.join(Path(f).name for f in files)} → {failure.code}: {failure.message} → {FALLBACK['name']} ({elapsed:.1f} s)")
            return {"ok": False, "decision": FALLBACK["bin"], "bin": FALLBACK["bin"], "slot": FALLBACK["slot"], "error": failure.code, "message": failure.message, "attempts": attempts, "item_id": (failure.details or {}).get("item_id") if isinstance(failure.details, dict) else None}
        attempts.append(result.item_id)
        if result.command_code != REUNFOLD:  # SORT (0) or TRASH (2): the garment goes to result.bin
            break
        short = ", ".join(f"{b['field']} {b['confidence']:.2f} < {b['threshold']:.2f}" for b in result.below) or (result.path[0].get("value") if result.path else "") or "test signals"
        print(f"attempt {result.attempt} of {result.max_attempts}: REUNFOLD ({short}) → new unfolding sequence")
        retry_of = result.item_id
        files = reunfold_and_photograph(files)
    decision = result.decide(min_confidence=args.min_confidence)
    elapsed = time.monotonic() - started
    label = "TRASH, retries used up → " if result.command_code == TRASH else "SORT (no answer in time, fallback bin) → " if result.degraded else "SORT → "
    server = result.timing.get("total")
    print(f"{result.summary()} → {label}{result.bin_name or decision} ({elapsed:.1f} s{f', server {server / 1000:.1f} s' if server else ''})")
    return {"ok": True, "decision": decision, "action": result.action, "command": result.command, "command_code": result.command_code, "bin": result.bin, "slot": result.slot, "bin_name": result.bin_name, "attempt": result.attempt, "attempts": attempts, "path": [f"{s.get('field')}={s.get('value')}→{s.get('outlet')}" for s in result.path], "sort_reason": result.sort_reason, "degraded": result.degraded, "item_id": result.item_id, "garment_type": result.garment_type, "grade": result.grade, "route": result.route, "confidence": result.confidence("recommended_route"), "seconds": round(elapsed, 1)}


def watch(vision: CikadaVision, folder: Path, args) -> int:
    """Every new image in the folder is one garment. Files that share a stem
    before an underscore (garment12_front.jpg, garment12_label.jpg) are sent
    together once no new file has appeared for --settle seconds."""
    seen: set[str] = set()
    failures = 0
    print(f"watching {folder} every {args.interval} s; Ctrl+C to stop")
    while True:
        fresh = sorted(p for p in folder.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES and str(p) not in seen)
        if fresh and time.time() - max(p.stat().st_mtime for p in fresh) >= args.settle:
            groups: dict[str, list[str]] = {}
            for path in fresh:
                groups.setdefault(path.stem.split("_")[0], []).append(str(path))
                seen.add(str(path))
            for files in groups.values():
                if not sort_garment(vision, files, args)["ok"]:
                    failures += 1
        time.sleep(args.interval)
        if args.max_garments and len(seen) >= args.max_garments:
            return 1 if failures else 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--once", nargs="+", metavar="IMAGE", help="classify one garment from these image files")
    parser.add_argument("--watch", metavar="FOLDER", help="classify every new image that appears in this folder")
    parser.add_argument("--separate", action="store_true", help="with --once: treat every file as its own garment")
    parser.add_argument("--async", dest="use_async", action="store_true", help="queue and poll instead of the sync endpoint")
    parser.add_argument("--early", type=float, metavar="SECONDS", help="send the photos at capture and ask for the bin this many seconds later, at the diverter")
    parser.add_argument("--decision-wait", dest="decision_wait", type=float, default=None, help="with --early: seconds to wait at the diverter before the fallback bin (default: the server's budget)")
    parser.add_argument("--robot", default=os.environ.get("CIKADA_ROBOT_ID") or None, help="robot id from /robots")
    parser.add_argument("--batch", metavar="NAME", help="create a batch with this name and put the garments in it")
    parser.add_argument("--external-ref", dest="external_ref", help="your own id for the garment (once mode)")
    parser.add_argument("--min-confidence", dest="min_confidence", type=float, default=0.6, help="below this the garment goes to review (default 0.6)")
    parser.add_argument("--timeout", type=float, default=40.0, help="seconds the robot waits per photo, retries included (default 40); then the fallback bin")
    parser.add_argument("--interval", type=float, default=2.0, help="watch: seconds between folder scans")
    parser.add_argument("--settle", type=float, default=1.0, help="watch: seconds a file must be unchanged before sending")
    parser.add_argument("--max-garments", dest="max_garments", type=int, default=0, help="watch: stop after this many files (0 = forever)")
    parser.add_argument("--base-url", dest="base_url", default=os.environ.get("CIKADA_BASE_URL", "https://vision.cikadasolutions.com"))
    args = parser.parse_args()

    api_key = os.environ.get("CIKADA_API_KEY")
    if not api_key:
        print("set CIKADA_API_KEY to the robot's API key (create one under Settings → API keys)", file=sys.stderr)
        return 2
    vision = CikadaVision(api_key=api_key, base_url=args.base_url, timeout=min(30.0, args.timeout), deadline=args.timeout)
    args.batch_id = vision.create_batch(args.batch) if args.batch else None
    try:
        sorting = vision.sorting(robot_id=args.robot)
        bins = {b["id"]: b for b in sorting.get("bins", [])}
        unsure = bins.get(sorting["unsure"], {"name": sorting["unsure"], "slot": None})
        FALLBACK.update(bin=sorting["unsure"], name=unsure["name"], slot=unsure.get("slot"))
        print(f"bins ({sorting.get('source', 'organization')}): " + ", ".join(f"slot {b.get('slot')} {b['id']} = {b['name']}" for b in bins.values()) + f"; no answer → {FALLBACK['name']}")
    except (CikadaVisionError, KeyError):
        print("sorting rules unavailable (older server); unanswered garments → review")

    if args.once:
        garments = [[f] for f in args.once] if args.separate else [args.once]
        results = [sort_garment(vision, files, args) for files in garments]
        print(json.dumps(results[-1]))
        return 0 if all(r["ok"] for r in results) else 1
    if args.watch:
        return watch(vision, Path(args.watch), args)
    parser.print_help()
    return 2


if __name__ == "__main__":
    sys.exit(main())
