"""Shared utility functions for gcplocal services."""

import time
import uuid
from typing import Any, Dict, Optional
from flask import jsonify, request


def gcp_id() -> str:
    """Generate a numeric-style GCP resource ID."""
    return str(uuid.uuid4().int)[:19]


def self_link(request_obj, path: str) -> str:
    """Build a selfLink URL from the current request context."""
    base = request_obj.host_url.rstrip("/")
    return f"{base}{path}"


def timestamp_now() -> str:
    return time.strftime("%Y-%m-%dT%H:%M:%S.000-00:00", time.gmtime())


def error_response(code: int, message: str, status: str = "NOT_FOUND"):
    """Return a standard GCP-style error JSON response."""
    return (
        jsonify(
            {
                "error": {
                    "code": code,
                    "message": message,
                    "status": status,
                    "errors": [
                        {
                            "message": message,
                            "domain": "global",
                            "reason": status.lower(),
                        }
                    ],
                }
            }
        ),
        code,
    )


def parse_field_mask(request_obj) -> Optional[list]:
    """Parse updateMask query parameter used in PATCH requests."""
    mask = request_obj.args.get("updateMask")
    if mask:
        return [f.strip() for f in mask.split(",")]
    return None


def paginate(items: list, request_obj, kind: str) -> Dict[str, Any]:
    """Apply GCP-style pagination to a list of items."""
    max_results = request_obj.args.get("maxResults", type=int, default=500)
    page_token = request_obj.args.get("pageToken", default=None)

    start_idx = 0
    if page_token:
        try:
            start_idx = int(page_token)
        except ValueError:
            start_idx = 0

    end_idx = start_idx + max_results
    page = items[start_idx:end_idx]

    result = {"kind": kind, "items": page}

    if end_idx < len(items):
        result["nextPageToken"] = str(end_idx)

    return result
