"""Cikada Vision client for robots and scripts.

Standard library only (Python 3.9+): copy this file next to your code, or
download it from https://vision.cikadasolutions.com/clients/cikada_vision.py

    from cikada_vision import CikadaVision

    vision = CikadaVision(api_key=os.environ["CIKADA_API_KEY"])
    result = vision.classify([("front.jpg", "front"), ("label.jpg", "label")], robot_id=ROBOT_ID)
    if result.command_code == REUNFOLD:   # 1: start a new unfolding sequence, send again with retry_of
        ...
    else:                                 # SORT (0) or TRASH (2): put it in result.bin / result.slot
        ...

Every call is scoped to the organization that owns the API key. Errors raise
``CikadaVisionError`` with the API's ``code`` and ``message``. Requests that
fail with a network error, a 5xx or a 429 are retried with the same
``Idempotency-Key``, so a retry never creates a duplicate item (``/classify/sync``
included since server D106). A ``model_error`` is not retried: the same photos
would get the same answer. Every call, retries included, finishes within
``deadline`` seconds (default 40), so the robot is never left waiting.

When the server has no classification within its time budget it answers with
the fallback bin and ``result.degraded`` is True: put the garment in
``result.bin`` (the bin people sort by hand) and carry on.

Photograph early, decide late: ``submit()`` the photos as soon as they are
taken, move the garment on, and call ``decision(item_id, wait=...)`` when it
reaches the diverter. The model's seconds then overlap the handling; when the
answer is still not in after ``wait``, the server records the fallback bin as
the garment's decision and returns it with ``degraded`` set.
"""
from __future__ import annotations

import json
import mimetypes
import os
import random
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
from urllib import error, parse, request

__all__ = ["CikadaVision", "CikadaVisionError", "Classification", "ROUTES", "VIEWS", "SORT", "REUNFOLD", "TRASH", "COMMANDS"]
__version__ = "1.11.0"

DEFAULT_BASE_URL = "https://vision.cikadasolutions.com"
VIEWS = ("front", "back", "label", "detail", "unknown")
ROUTES = ("reuse", "repair", "recycle_fiber", "waste")

# Robot commands: fixed names and numbers, never renumbered.
SORT = 0       # put the garment in result.bin at result.slot
REUNFOLD = 1   # start a new unfolding sequence, photograph again, send with retry_of=result.item_id
TRASH = 2      # the retries are used up: put the garment in result.bin (the bin after the last retry)
COMMANDS = {SORT: "SORT", REUNFOLD: "REUNFOLD", TRASH: "TRASH"}
_ACTION_COMMANDS = {"sort": SORT, "retry": REUNFOLD, "discard": TRASH}
MAX_IMAGES = 6
MAX_IMAGE_BYTES = 20 * 1024 * 1024

ImageSource = Union[str, "os.PathLike[str]", bytes]
ImageSpec = Union[ImageSource, Tuple[ImageSource, str]]


class CikadaVisionError(Exception):
    """An error returned by the API or raised while talking to it.

    ``code`` follows the API contract: validation_error, unauthorized, forbidden,
    not_found, rate_limited, model_error, internal, plus ``network`` for
    connection failures and ``timeout`` when ``wait_for`` gives up.
    """

    def __init__(self, code: str, message: str, details: Any = None, status: Optional[int] = None):
        super().__init__(f"{code}: {message}")
        self.code = code
        self.message = message
        self.details = details
        self.status = status


@dataclass
class Classification:
    """One garment as the API returns it, with helpers for sorting decisions."""

    item_id: str
    status: str
    attributes: Dict[str, Dict[str, Any]]
    raw: Dict[str, Any] = field(repr=False)
    # Milliseconds: ``round_trip_ms`` as the robot waited (retries included) and
    # the server's own stages from its Server-Timing header (server D163).
    timing: Dict[str, float] = field(default_factory=dict, repr=False)

    @classmethod
    def from_item(cls, item: Dict[str, Any]) -> "Classification":
        return cls(item_id=item["id"], status=item["status"], attributes=item.get("attributes") or {}, raw=item)

    def value(self, name: str) -> Optional[str]:
        attribute = self.attributes.get(name)
        return None if attribute is None else attribute.get("value")

    def confidence(self, name: str) -> float:
        attribute = self.attributes.get(name)
        return 0.0 if attribute is None else float(attribute.get("confidence", 0.0))

    @property
    def garment_type(self) -> Optional[str]:
        return self.value("garment_type")

    @property
    def grade(self) -> Optional[str]:
        return self.value("condition_grade")

    @property
    def route(self) -> Optional[str]:
        return self.value("recommended_route")

    def _observed(self, name: str) -> Optional[str]:
        classification = self.raw.get("classification")
        value = classification.get(name) if isinstance(classification, dict) else None
        return value if isinstance(value, str) else None

    @property
    def scene(self) -> Optional[str]:
        """What the photos showed (server D121): single, multiple, partial, empty or
        foreign_object; None for garments classified before the model reported it."""
        return self._observed("scene")

    @property
    def contamination(self) -> Optional[str]:
        """Contamination seen on the garment: none, wet, mould, heavy_soil or hazard; None when not reported."""
        return self._observed("contamination")

    @property
    def hard_parts(self) -> Optional[str]:
        """What the hard parts pass found (server D143): ``none``, ``metal``, ``plastic``
        or ``mixed``; ``not_checked`` when the pass did not run or did not answer in time;
        None on servers before client 1.9. The sorting logic's hard parts check already
        acted on it: ``command_code`` is SORT to the plant's bin for hard parts."""
        hard_parts = self.raw.get("hard_parts")
        if not isinstance(hard_parts, dict):
            return None
        summary = hard_parts.get("summary")
        return summary if isinstance(summary, str) else None

    @property
    def hard_part_findings(self) -> List[Dict[str, Any]]:
        """Each hard part found: kind, part, location, confidence, image_id and an approximate box in fractions of the original photo."""
        hard_parts = self.raw.get("hard_parts")
        findings = hard_parts.get("findings") if isinstance(hard_parts, dict) else None
        return [f for f in findings if isinstance(f, dict)] if isinstance(findings, list) else []

    @property
    def resale_price(self) -> Optional[Dict[str, Any]]:
        """The garment's estimated resale price (server D146), for garments going to
        reuse: ``{"status", "amount", "low", "high", "currency", "confidence", "basis",
        "source", ...}``. ``status`` is ``estimated`` (``amount`` is set; a person's price
        wins over the model's), ``unknown`` (too little to go on), ``pending`` (being
        estimated: it lands a few seconds after the classification, in the ``item.priced``
        webhook or on ``get_item``) or ``not_applicable`` (not a reuse garment, or the pass
        is off). None on servers before client 1.10. The price never changes the bin."""
        resale_price = self.raw.get("resale_price")
        return resale_price if isinstance(resale_price, dict) else None

    @property
    def resale_price_amount(self) -> Optional[float]:
        """The asking price in ``resale_price["currency"]`` when one is set, else None."""
        resale_price = self.resale_price
        if not resale_price or resale_price.get("status") != "estimated":
            return None
        amount = resale_price.get("amount")
        return float(amount) if isinstance(amount, (int, float)) else None

    @property
    def classified(self) -> bool:
        return self.status in ("classified", "reviewed")

    @property
    def needs_review(self) -> bool:
        """True when the model and the trained classifier disagree on garment
        type or category and nobody has reviewed the garment yet."""
        return self.status == "classified" and bool(self.raw.get("needs_review"))

    @property
    def bin(self) -> Optional[str]:
        """Bin id the server assigned when the garment was classified (e.g. ``"A"``),
        from the organization's sorting rules in Settings → Sorting; None before that."""
        sort = self.raw.get("sort")
        return sort.get("bin") if isinstance(sort, dict) else None

    @property
    def bin_name(self) -> Optional[str]:
        sort = self.raw.get("sort")
        return sort.get("name") if isinstance(sort, dict) else None

    @property
    def action(self) -> str:
        """``sort`` (put it in ``bin``), ``retry`` (re-unfold, photograph again and
        send with ``retry_of=item_id``) or ``discard`` (retries used up; put it in ``bin``)."""
        sort = self.raw.get("sort")
        return str(sort.get("action", "sort")) if isinstance(sort, dict) else "sort"

    @property
    def command_code(self) -> int:
        """The robot command as a number: ``SORT`` (0), ``REUNFOLD`` (1) or ``TRASH`` (2)."""
        sort = self.raw.get("sort")
        code = sort.get("command_code") if isinstance(sort, dict) else None
        if code in COMMANDS:
            return int(code)
        # Servers before client 1.6 send only ``action``; it maps one to one.
        return _ACTION_COMMANDS.get(self.action, SORT)

    @property
    def command(self) -> str:
        """The robot command by name: ``"SORT"``, ``"REUNFOLD"`` or ``"TRASH"``."""
        return COMMANDS[self.command_code]

    @property
    def attempt(self) -> int:
        return int(self.raw.get("attempt") or 1)

    @property
    def max_attempts(self) -> Optional[int]:
        sort = self.raw.get("sort")
        value = sort.get("max_attempts") if isinstance(sort, dict) else None
        return int(value) if value else None

    @property
    def below(self) -> List[Dict[str, Any]]:
        """Fields under the certainty the robot requires: ``[{"field", "confidence", "threshold"}]``."""
        sort = self.raw.get("sort")
        rows = sort.get("below") if isinstance(sort, dict) else None
        return list(rows) if isinstance(rows, list) else []

    @property
    def slot(self) -> Optional[int]:
        """The bin's position on the machine (1 = first), from the robot's bin order in Cikada Vision."""
        sort = self.raw.get("sort")
        return sort.get("slot") if isinstance(sort, dict) else None

    @property
    def path(self) -> List[Dict[str, Any]]:
        """The questions the garment passed on its way to the bin, in order:
        ``[{"field": "material_primary", "value": "cotton", "outlet": "cotton", ...}]``."""
        sort = self.raw.get("sort")
        steps = sort.get("path") if isinstance(sort, dict) else None
        return list(steps) if isinstance(steps, list) else []

    @property
    def degraded(self) -> bool:
        """True when the server answered with the fallback bin because no
        classification was ready within its time budget. The garment is still
        classified afterwards for review; its bin never changes."""
        sort = self.raw.get("sort")
        return bool(sort.get("degraded")) if isinstance(sort, dict) else False

    @property
    def sort_reason(self) -> Optional[str]:
        sort = self.raw.get("sort")
        return sort.get("reason") if isinstance(sort, dict) else None

    def decide(self, min_confidence: float = 0.6) -> str:
        """Where to put the garment, or ``"retry"`` when it must be re-unfolded and photographed again.

        Servers with sorting bins return the bin id they assigned (``self.bin``);
        unsure garments already go to the organization's "unsure" bin there.
        Older servers: one of ROUTES, or ``review`` when the model is not sure
        enough (or the item is not classified); ``min_confidence`` applies only
        to that fallback. A ``degraded`` answer (no classification in time) is
        the fallback bin the server chose; the garment is not classified yet."""
        if self.degraded and self.bin:
            return self.bin
        if self.classified and self.action == "retry":
            return "retry"
        if self.classified and self.bin:
            return self.bin
        route = self.route
        if not self.classified or route not in ROUTES or self.needs_review:
            return "review"
        if self.confidence("recommended_route") < min_confidence:
            return "review"
        return route

    def summary(self) -> str:
        where = f", {self.bin_name or 'bin ' + self.bin}" + (f" (slot {self.slot})" if self.slot else "") if self.bin else ""
        amount = self.resale_price_amount
        price = f", ≈ {self.resale_price.get('currency', '')} {amount:.0f}".rstrip() if amount is not None and self.resale_price else ""
        return (
            f"item {self.item_id[:8]} → {self.garment_type or '?'}, grade {self.grade or '?'}, "
            f"route {self.route or '?'} ({self.confidence('recommended_route'):.2f}){where}{price}"
        )


class CikadaVision:
    """HTTP client for the Cikada Vision API (``/api/v1``)."""

    def __init__(
        self,
        api_key: str,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = 30.0,
        retries: int = 3,
        user_agent: str = f"cikada-vision-python/{__version__}",
        deadline: float = 40.0,
    ):
        """``timeout``: seconds per HTTP request. ``deadline``: seconds a whole
        call may take, retries and waits included; past it the last error is
        raised so the robot can use its fallback bin."""
        if not api_key or not api_key.startswith("ck_"):
            raise CikadaVisionError("unauthorized", "an API key starting with ck_ is required")
        self._api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.retries = retries
        self.user_agent = user_agent
        self.deadline = deadline
        # The last successful call's timing, as on ``Classification.timing``.
        self.last_timing: Dict[str, float] = {}

    # ---- public API -----------------------------------------------------

    def classify(
        self,
        images: Sequence[ImageSpec],
        robot_id: Optional[str] = None,
        batch_id: Optional[str] = None,
        external_ref: Optional[str] = None,
        retry_of: Optional[str] = None,
        nir: Optional[Sequence[Dict[str, Any]]] = None,
    ) -> Classification:
        """Store one garment and classify it inline (``POST /classify/sync``).

        Blocks for the model's answer, typically 3–5 seconds for a robot's
        garment (server D163; ``result.timing`` says where they went) and never longer
        than the server's time budget (25 s by default): then the answer is the
        fallback bin with ``degraded`` set. Raises
        ``CikadaVisionError('model_error')`` when the model could not produce a
        valid classification; the item is still stored for review.

        After an answer with ``action == "retry"``, re-unfold and photograph the
        garment and call again with ``retry_of=<that item's id>``.

        ``nir`` is the robot's NIR fibre reading, e.g.
        ``[{"fiber": "cotton", "percent": 92.5}]``; the sorting logic uses it
        before a care label or the simulation from the model's material."""
        body, content_type = self._multipart(images, robot_id, batch_id, external_ref, retry_of, nir)
        item = self._request("POST", "/classify/sync", body, content_type, idempotent=True)
        return self._timed(Classification.from_item(item))

    def submit(
        self,
        images: Sequence[ImageSpec],
        robot_id: Optional[str] = None,
        batch_id: Optional[str] = None,
        external_ref: Optional[str] = None,
        retry_of: Optional[str] = None,
        nir: Optional[Sequence[Dict[str, Any]]] = None,
    ) -> str:
        """Store one garment and queue it (``POST /items``). Returns the item id at once."""
        body, content_type = self._multipart(images, robot_id, batch_id, external_ref, retry_of, nir)
        accepted = self._request("POST", "/items", body, content_type, idempotent=True)
        return accepted["item_id"]

    def decision(self, item_id: str, wait: Optional[float] = None) -> Classification:
        """The bin for a garment sent ahead with ``submit()`` (``POST /items/{id}/decision``).

        Call it when the garment reaches the diverter. Waits up to ``wait``
        seconds for the classification (default and maximum: the server's time
        budget, 25 s by default). When it is still not in, the server records the
        fallback bin as the garment's decision and the result has ``degraded``
        set; the garment keeps that bin when it is classified afterwards. Asking
        again returns the same decision. Raises
        ``CikadaVisionError('model_error')`` when the model could not classify
        the garment."""
        payload = json.dumps({} if wait is None else {"wait_ms": max(0, int(wait * 1000))}).encode()
        item = self._request("POST", f"/items/{parse.quote(item_id)}/decision", payload, "application/json", idempotent=True)
        return self._timed(Classification.from_item(item))

    def get_item(self, item_id: str) -> Classification:
        return Classification.from_item(self._request("GET", f"/items/{item_id}"))

    def wait_for(self, item_id: str, timeout: float = 60.0, poll_interval: float = 2.0) -> Classification:
        """Poll until a submitted item is classified, reviewed or failed."""
        deadline = time.monotonic() + timeout
        while True:
            item = self.get_item(item_id)
            if item.status in ("classified", "reviewed"):
                return item
            if item.status == "failed":
                raise CikadaVisionError("model_error", item.raw.get("error") or "classification failed", status=200)
            if time.monotonic() >= deadline:
                raise CikadaVisionError("timeout", f"item {item_id} still {item.status} after {timeout:.0f} s")
            time.sleep(poll_interval)

    def reclassify(self, item_id: str) -> str:
        accepted = self._request("POST", f"/items/{item_id}/classify", b"", "application/json", idempotent=True)
        return accepted["item_id"]

    def create_batch(self, name: str, source: str = "robot") -> str:
        payload = json.dumps({"name": name, "source": source}).encode()
        return self._request("POST", "/batches", payload, "application/json", idempotent=True)["id"]

    def sorting(self, robot_id: Optional[str] = None) -> Dict[str, Any]:
        """The bins and rules this robot sorts by (its own, else the organization's):
        ``{"source": "robot", "bins": [{"id", "name", "slot"}], "by_category": {...}, "unsure": "C"}``.
        Read it at start-up to check the machine knows every bin id and slot."""
        query = f"?robot_id={parse.quote(robot_id)}" if robot_id else ""
        return self._request("GET", f"/sorting{query}")

    def taxonomy(self) -> Dict[str, Any]:
        return self._request("GET", "/taxonomy")

    def health(self) -> Dict[str, Any]:
        return self._request("GET", "/health")

    # ---- internals ------------------------------------------------------

    def _multipart(
        self,
        images: Sequence[ImageSpec],
        robot_id: Optional[str],
        batch_id: Optional[str],
        external_ref: Optional[str],
        retry_of: Optional[str] = None,
        nir: Optional[Sequence[Dict[str, Any]]] = None,
    ) -> Tuple[bytes, str]:
        specs = list(images)
        if not specs:
            raise CikadaVisionError("validation_error", "send at least one image")
        if len(specs) > MAX_IMAGES:
            raise CikadaVisionError("validation_error", f"at most {MAX_IMAGES} images per garment")
        boundary = f"----cikada-{uuid.uuid4().hex}"
        parts: List[bytes] = []

        def text_field(name: str, value: str) -> None:
            parts.append(
                f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n".encode()
            )

        for index, spec in enumerate(specs):
            source, view = (spec if isinstance(spec, tuple) else (spec, "unknown"))
            if view not in VIEWS:
                raise CikadaVisionError("validation_error", f"view must be one of {', '.join(VIEWS)}")
            if isinstance(source, (bytes, bytearray)):
                data, filename = bytes(source), f"image-{index + 1}.jpg"
            else:
                path = os.fspath(source)
                with open(path, "rb") as handle:
                    data = handle.read()
                filename = os.path.basename(path) or f"image-{index + 1}"
            if len(data) > MAX_IMAGE_BYTES:
                raise CikadaVisionError("validation_error", f"{filename} is larger than 20 MB")
            mime = mimetypes.guess_type(filename)[0] or "application/octet-stream"
            parts.append(
                (
                    f"--{boundary}\r\nContent-Disposition: form-data; name=\"image[]\"; filename=\"{filename}\"\r\n"
                    f"Content-Type: {mime}\r\n\r\n"
                ).encode()
                + data
                + b"\r\n"
            )
            text_field("view[]", view)
        if robot_id:
            text_field("robot_id", robot_id)
        if batch_id:
            text_field("batch_id", batch_id)
        if external_ref:
            text_field("external_ref", external_ref)
        if retry_of:
            text_field("retry_of", retry_of)
        if nir:
            reading = [{"fiber": str(f["fiber"]), "percent": float(f["percent"])} for f in nir]
            if not 1 <= len(reading) <= 10 or any(not 0 <= f["percent"] <= 100 for f in reading):
                raise CikadaVisionError("validation_error", "nir: 1 to 10 fibres, each 0 to 100 percent")
            text_field("nir", json.dumps(reading))
        parts.append(f"--{boundary}--\r\n".encode())
        return b"".join(parts), f"multipart/form-data; boundary={boundary}"

    def _request(
        self,
        method: str,
        path: str,
        body: Optional[bytes] = None,
        content_type: Optional[str] = None,
        idempotent: bool = False,
    ) -> Any:
        url = f"{self.base_url}/api/v1{path}"
        headers = {"Authorization": f"Bearer {self._api_key}", "Accept": "application/json", "User-Agent": self.user_agent}
        if body is not None and content_type:
            headers["Content-Type"] = content_type
        if idempotent:
            headers["Idempotency-Key"] = str(uuid.uuid4())

        started = time.monotonic()
        give_up_at = started + self.deadline
        last_error: Optional[CikadaVisionError] = None
        for attempt in range(self.retries + 1):
            remaining = give_up_at - time.monotonic()
            if remaining < 1.0:
                break
            req = request.Request(url, data=body, headers=headers, method=method)
            try:
                with request.urlopen(req, timeout=min(self.timeout, remaining)) as response:
                    decoded = self._decode(response.read(), response.status)
                    self.last_timing = {
                        "round_trip_ms": round((time.monotonic() - started) * 1000),
                        **self._server_timing(response.headers.get("Server-Timing")),
                    }
                    return decoded
            except error.HTTPError as http_error:
                payload = http_error.read()
                api_error = self._to_error(payload, http_error.code)
                retry_after = http_error.headers.get("Retry-After")
                # A model_error is final: the same photos get the same answer, and a retry costs a model call.
                retryable = http_error.code == 429 or (http_error.code >= 500 and api_error.code != "model_error")
                if not retryable:
                    raise api_error
                last_error = api_error
                if attempt < self.retries and self._wait(attempt, retry_after, give_up_at):
                    continue
                raise api_error
            except (error.URLError, TimeoutError, OSError) as network_error:
                last_error = CikadaVisionError("network", str(getattr(network_error, "reason", network_error)))
                if attempt < self.retries and self._wait(attempt, None, give_up_at):
                    continue
                raise last_error
        raise last_error or CikadaVisionError("timeout", f"no answer within {self.deadline:.0f} s")

    def _timed(self, result: Classification) -> Classification:
        result.timing = dict(self.last_timing)
        return result

    @staticmethod
    def _server_timing(header: Optional[str]) -> Dict[str, float]:
        """``parse;dur=40, ingest;dur=610`` -> ``{"parse": 40.0, "ingest": 610.0}``; unreadable parts are skipped."""
        stages: Dict[str, float] = {}
        for part in (header or "").split(","):
            name, _, rest = part.strip().partition(";")
            for parameter in rest.split(";"):
                key, _, value = parameter.strip().partition("=")
                if name and key == "dur":
                    try:
                        stages[name] = float(value)
                    except ValueError:
                        pass
        return stages

    def _wait(self, attempt: int, retry_after: Optional[str], give_up_at: float) -> bool:
        """Sleeps before the next attempt; False when that attempt would start too late to finish."""
        delay = self._delay(attempt, retry_after)
        if time.monotonic() + delay + 1.0 > give_up_at:
            return False
        time.sleep(delay)
        return True

    @staticmethod
    def _delay(attempt: int, retry_after: Optional[str]) -> float:
        if retry_after:
            try:
                return max(0.0, float(retry_after))
            except ValueError:
                pass
        return min(20.0, 0.5 * (2 ** attempt)) + random.uniform(0, 0.25)

    @staticmethod
    def _decode(payload: bytes, status: int) -> Any:
        if not payload:
            return {}
        try:
            return json.loads(payload.decode("utf-8"))
        except ValueError:
            raise CikadaVisionError("internal", f"unexpected non-JSON response (HTTP {status})", status=status)

    @staticmethod
    def _to_error(payload: bytes, status: int) -> CikadaVisionError:
        try:
            body = json.loads(payload.decode("utf-8"))
            err = body["error"]
            return CikadaVisionError(err.get("code", "internal"), err.get("message", f"HTTP {status}"), err.get("details"), status)
        except (ValueError, KeyError, TypeError, AttributeError):
            code = "rate_limited" if status == 429 else "internal"
            return CikadaVisionError(code, f"HTTP {status}", None, status)


def iter_garment_files(paths: Iterable[str]) -> List[Tuple[str, str]]:
    """Guess the view of each file from its name (front/back/label/detail)."""
    out: List[Tuple[str, str]] = []
    for path in paths:
        lower = os.path.basename(path).lower()
        view = next((v for v in VIEWS if v != "unknown" and v in lower), "unknown")
        out.append((path, view))
    return out
