"""Python 3.10+ quickstart for Recipe API (stdlib only — no pip install needed).

Run:
    RECIPE_API_KEY=rapi_your_key python3 recipe_quickstart.py

Uses 2 requests: 1 filtered search + 1 full recipe lookup.
Never place your API key in client-side code or a public repository.
"""

from __future__ import annotations

from dataclasses import dataclass
import json
import os
import sys
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

BASE_URL = "https://recipe-api.com/api/v1"


@dataclass(frozen=True)
class RecipeCard:
    id: str
    name: str
    cuisine: str | None
    calories: float | None
    protein_g: float | None


def api_get(path: str, api_key: str, params: dict[str, str | int] | None = None) -> dict:
    url = f"{BASE_URL}/{path.lstrip('/')}"
    if params:
        url = f"{url}?{urlencode(params)}"
    req = Request(url, headers={"X-API-Key": api_key, "Accept": "application/json"})
    try:
        with urlopen(req, timeout=30) as response:
            return json.loads(response.read().decode("utf-8"))
    except HTTPError as err:
        retry_after = err.headers.get("Retry-After")
        hint = f" Retry after {retry_after}s." if retry_after else " Check your key and quota."
        raise RuntimeError(f"Recipe API returned HTTP {err.code}.{hint}") from err


def search_high_protein_dinners(api_key: str) -> list[RecipeCard]:
    payload = api_get(
        "recipes",
        api_key,
        {
            "category": "Dinner",
            "max_calories": 600,
            "min_protein": 30,
            "per_page": 5,
        },
    )
    cards: list[RecipeCard] = []
    for item in payload.get("data", []):
        summary = item.get("nutrition_summary") or {}
        cards.append(
            RecipeCard(
                id=item["id"],
                name=item["name"],
                cuisine=item.get("cuisine"),
                calories=summary.get("calories"),
                protein_g=summary.get("protein_g"),
            )
        )
    return cards


def main() -> None:
    api_key = os.environ.get("RECIPE_API_KEY")
    if not api_key:
        print("Set RECIPE_API_KEY before running this script.", file=sys.stderr)
        sys.exit(1)

    cards = search_high_protein_dinners(api_key)
    if not cards:
        print("No recipes matched those filters.")
        return

    detail = api_get(f"recipes/{cards[0].id}", api_key)
    recipe = detail["data"]
    per_serving = recipe["nutrition"]["per_serving"]
    output = {
        "matches": [card.__dict__ for card in cards],
        "selected": {
            "id": recipe["id"],
            "name": recipe["name"],
            "yields": recipe["meta"]["yields"],
            "calories": per_serving["calories"],
            "protein_g": per_serving["protein_g"],
            "iron_mg": per_serving["iron_mg"],
            "ingredient_groups": len(recipe["ingredients"]),
            "steps": len(recipe["instructions"]),
        },
        "usage": detail.get("usage"),
    }
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()
