# Generated by ariadne-codegen
# Source: hubsrht/services/hg/

from typing import Any, Optional, Union

import httpx
from flask import has_request_context, request
from srht.config import cfg, get_origin
from srht.graphql import InternalAuth

from .base_client import BaseClient
from .base_model import UNSET, UnsetType
from .create_repo import CreateRepo
from .create_user_webhook import CreateUserWebhook
from .delete_repo import DeleteRepo
from .delete_user_webhook import DeleteUserWebhook
from .enums import Visibility
from .event_webhook import EventWebhook
from .get_readme import GetReadme
from .get_repo import GetRepo
from .get_repos import GetRepos


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


class HgClient(BaseClient):
    def __init__(self, auth=None, headers=None, client=None, **kwargs):
        origin = cfg("hg.sr.ht", "api-origin", default=get_origin("hg.sr.ht"))
        if auth is None:
            auth = InternalAuth()
        headers = {**auth.headers, "User-Agent": "hg.sr.ht frontend"}
        if has_request_context():
            headers["X-Forwarded-For"] = ", ".join(request.access_route)
        if not client:
            backend_timeout = cfg("hg.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_repos(
        self, cursor: Union[Optional[Any], UnsetType] = UNSET, **kwargs: Any
    ) -> GetRepos:
        query = gql("""
            query GetRepos($cursor: Cursor) {
              me {
                repositories(cursor: $cursor) {
                  results {
                    id
                    rid
                    name
                    updated
                    owner {
                      __typename
                      canonicalName
                    }
                  }
                  cursor
                }
              }
            }
            """)
        variables: dict[str, object] = {"cursor": cursor}
        response = self.execute(
            query=query, operation_name="GetRepos", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetRepos.model_validate(data)

    def get_repo(self, rid: str, **kwargs: Any) -> GetRepo:
        query = gql("""
            query GetRepo($rid: ID!) {
              repository(rid: $rid) {
                id
                rid
                name
                description
                visibility
              }
            }
            """)
        variables: dict[str, object] = {"rid": rid}
        response = self.execute(
            query=query, operation_name="GetRepo", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetRepo.model_validate(data)

    def get_readme(self, username: str, repo_name: str, **kwargs: Any) -> GetReadme:
        query = gql("""
            query GetReadme($username: String!, $repoName: String!) {
              user(username: $username) {
                repository(name: $repoName) {
                  html: readme
                  md: cat(path: "README.md")
                  markdown: cat(path: "README.markdown")
                  plaintext: cat(path: "README")
                }
              }
            }
            """)
        variables: dict[str, object] = {"username": username, "repoName": repo_name}
        response = self.execute(
            query=query, operation_name="GetReadme", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetReadme.model_validate(data)

    def create_repo(
        self,
        name: str,
        visibility: Visibility,
        description: Union[Optional[str], UnsetType] = UNSET,
        **kwargs: Any,
    ) -> CreateRepo:
        query = gql("""
            mutation CreateRepo($name: String!, $visibility: Visibility!, $description: String) {
              repository: createRepository(
                name: $name
                description: $description
                visibility: $visibility
              ) {
                id
                rid
                name
                description
                visibility
              }
            }
            """)
        variables: dict[str, object] = {
            "name": name,
            "visibility": visibility,
            "description": description,
        }
        response = self.execute(
            query=query, operation_name="CreateRepo", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return CreateRepo.model_validate(data)

    def delete_repo(self, repo_id: int, **kwargs: Any) -> DeleteRepo:
        query = gql("""
            mutation DeleteRepo($repo_id: Int!) {
              deleteRepository(id: $repo_id) {
                id
              }
            }
            """)
        variables: dict[str, object] = {"repo_id": repo_id}
        response = self.execute(
            query=query, operation_name="DeleteRepo", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return DeleteRepo.model_validate(data)

    def create_user_webhook(
        self, payload: str, url: str, **kwargs: Any
    ) -> CreateUserWebhook:
        query = gql("""
            mutation CreateUserWebhook($payload: String!, $url: String!) {
              webhook: createUserWebhook(
                config: {url: $url, events: [REPO_UPDATE, REPO_DELETED], query: $payload}
              ) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {"payload": payload, "url": url}
        response = self.execute(
            query=query,
            operation_name="CreateUserWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return CreateUserWebhook.model_validate(data)

    def delete_user_webhook(self, id: int, **kwargs: Any) -> DeleteUserWebhook:
        query = gql("""
            mutation DeleteUserWebhook($id: Int!) {
              deleteUserWebhook(id: $id) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query,
            operation_name="DeleteUserWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return DeleteUserWebhook.model_validate(data)

    def event_webhook(self, **kwargs: Any) -> EventWebhook:
        query = gql("""
            query EventWebhook {
              webhook {
                __typename
                uuid
                event
                date
                ... on RepositoryEvent {
                  repository {
                    id
                    rid
                    name
                    description
                    visibility
                  }
                }
              }
            }
            """)
        variables: dict[str, object] = {}
        response = self.execute(
            query=query, operation_name="EventWebhook", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return EventWebhook.model_validate(data)

    get_repos_query = "query GetRepos($cursor: Cursor) {\n  me {\n    repositories(cursor: $cursor) {\n      results {\n        id\n        rid\n        name\n        updated\n        owner {\n          __typename\n          canonicalName\n        }\n      }\n      cursor\n    }\n  }\n}"
    get_repo_query = "query GetRepo($rid: ID!) {\n  repository(rid: $rid) {\n    id\n    rid\n    name\n    description\n    visibility\n  }\n}"
    get_readme_query = 'query GetReadme($username: String!, $repoName: String!) {\n  user(username: $username) {\n    repository(name: $repoName) {\n      html: readme\n      md: cat(path: "README.md")\n      markdown: cat(path: "README.markdown")\n      plaintext: cat(path: "README")\n    }\n  }\n}'
    create_repo_query = "mutation CreateRepo($name: String!, $visibility: Visibility!, $description: String) {\n  repository: createRepository(\n    name: $name\n    description: $description\n    visibility: $visibility\n  ) {\n    id\n    rid\n    name\n    description\n    visibility\n  }\n}"
    delete_repo_query = "mutation DeleteRepo($repo_id: Int!) {\n  deleteRepository(id: $repo_id) {\n    id\n  }\n}"
    create_user_webhook_query = "mutation CreateUserWebhook($payload: String!, $url: String!) {\n  webhook: createUserWebhook(\n    config: {url: $url, events: [REPO_UPDATE, REPO_DELETED], query: $payload}\n  ) {\n    __typename\n    id\n  }\n}"
    delete_user_webhook_query = "mutation DeleteUserWebhook($id: Int!) {\n  deleteUserWebhook(id: $id) {\n    __typename\n    id\n  }\n}"
    event_webhook_query = "query EventWebhook {\n  webhook {\n    __typename\n    uuid\n    event\n    date\n    ... on RepositoryEvent {\n      repository {\n        id\n        rid\n        name\n        description\n        visibility\n      }\n    }\n  }\n}"
