"""Deterministic partial-failure exercise. Python 3.10+, no network or accounts."""
from concurrent.futures import ThreadPoolExecutor, as_completed
import json


class InvalidPayload(Exception):
    pass


def collect_one(name, connector, max_attempts=2):
    if max_attempts < 1:
        raise ValueError("max_attempts must be positive")
    for attempt in range(1, max_attempts + 1):
        try:
            rows = connector()
            if not isinstance(rows, list) or any(
                not isinstance(row, dict) or not isinstance(row.get("id"), str)
                or not row["id"] for row in rows
            ):
                raise InvalidPayload()
        except TimeoutError:
            if attempt < max_attempts:
                continue
            kind = "timeout"
        except PermissionError:
            kind = "authentication"
        except InvalidPayload:
            kind = "invalid_payload"
        else:
            unique = {row["id"]: row for row in rows}
            return {"source": name, "status": "ok", "attempts": attempt,
                    "items": [unique[key] for key in sorted(unique)]}
        return {"source": name, "status": "unavailable", "reason": kind,
                "attempts": attempt, "items": []}


def collect(connectors):
    outcomes = []
    with ThreadPoolExecutor(max_workers=4) as pool:
        pending = {pool.submit(collect_one, name, connector): name
                   for name, connector in connectors.items()}
        for future in as_completed(pending):
            # Unexpected programmer errors propagate; they are not provider outages.
            outcomes.append(future.result())
    outcomes.sort(key=lambda outcome: outcome["source"])
    healthy = sum(outcome["status"] == "ok" for outcome in outcomes)
    count = sum(len(outcome["items"]) for outcome in outcomes)
    return {"coverage": f"{healthy} of {len(outcomes)} sources checked",
            "item_count": count, "complete": healthy == len(outcomes), "sources": outcomes}


def fixture_connectors():
    def timeout():
        raise TimeoutError("synthetic timeout")

    def authentication():
        raise PermissionError("synthetic authentication failure")

    attempts = 0

    def recovered():
        nonlocal attempts
        attempts += 1
        if attempts == 1:
            raise TimeoutError("synthetic temporary timeout")
        return [{"id": "recovered-1"}]

    return {"healthy": lambda: [{"id": "a"}, {"id": "b"}, {"id": "a"}],
            "empty": lambda: [], "timeout": timeout, "authentication": authentication,
            "malformed": lambda: {"unexpected": []}, "recovered": recovered}


if __name__ == "__main__":
    print(json.dumps(collect(fixture_connectors()), indent=2))
