from datetime import date

from quart import jsonify, request


def not_found(resource: str = "Item"):
    return jsonify({"error": f"{resource} not found"}), 404


def parse_iso_date(value: str | None, field: str = "date"):
    """Parse an ISO date string. Returns a date, None, or a (response, 400) tuple."""
    if not value:
        return None
    try:
        return date.fromisoformat(value)
    except ValueError:
        return jsonify({"error": f"Invalid {field} format. Use YYYY-MM-DD."}), 400


def parse_pagination(default_limit: int = 50, max_limit: int = 500) -> tuple[int, int]:
    """Extract and clamp ``limit`` / ``offset`` from the current request's query string."""
    limit = min(request.args.get("limit", default_limit, type=int), max_limit)
    offset = request.args.get("offset", 0, type=int)
    return limit, offset
