# Generated by ariadne-codegen
# Source: srht/services/hub/

from typing import Any

import httpx
from flask import has_request_context, request

from srht.config import cfg, get_api
from srht.graphql import InternalAuth

from .base_client import BaseClient
from .get_resource_projects import GetResourceProjects


def gql(q: str) -> str:
    return q


class HubClient(BaseClient):
    def __init__(self, auth=None, headers=None, client=None, **kwargs):
        origin = get_api("hub.sr.ht")
        if auth is None:
            auth = InternalAuth()
        headers = {**auth.headers, "User-Agent": "hub.sr.ht frontend"}
        if has_request_context():
            headers["X-Forwarded-For"] = ", ".join(request.access_route)
        if not client:
            backend_timeout = cfg("hub.sr.ht", "backend-timeout", default=3)
            client = httpx.Client(
                headers=headers, timeout=httpx.Timeout(int(backend_timeout))
            )
        super().__init__(origin + "/query", headers, client, **kwargs)

    def get_resource_projects(self, rid: str, **kwargs: Any) -> GetResourceProjects:
        query = gql("""
            query GetResourceProjects($rid: ID!) {
              resource(rid: $rid) {
                __typename
                name
                projects {
                  results {
                    ...projectResources
                  }
                }
              }
            }

            fragment projectResources on Project {
              name
              owner {
                __typename
                canonicalName
              }
              mailingLists {
                results {
                  rid
                  name
                }
              }
              sources {
                results {
                  rid
                  name
                  repoType
                }
              }
              trackers {
                results {
                  rid
                  name
                }
              }
            }
            """)
        variables: dict[str, object] = {"rid": rid}
        response = self.execute(
            query=query,
            operation_name="GetResourceProjects",
            variables=variables,
            **kwargs
        )
        data = self.get_data(response)
        return GetResourceProjects.model_validate(data)

    get_resource_projects_query = "query GetResourceProjects($rid: ID!) {\n  resource(rid: $rid) {\n    __typename\n    name\n    projects {\n      results {\n        ...projectResources\n      }\n    }\n  }\n}"
