# Generated by ariadne-codegen
# Source: mansrht/git/

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 .delete_repo import DeleteRepo
from .enums import Visibility
from .get_references import GetReferences
from .get_repo import GetRepo
from .get_repo_access import GetRepoAccess
from .get_repos import GetRepos
from .get_root_tree import GetRootTree
from .get_tree import GetTree


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


class GitClient(BaseClient):
    def __init__(self, auth=None, headers=None, client=None, **kwargs):
        origin = cfg("git.sr.ht", "api-origin", default=get_origin("git.sr.ht"))
        if auth is None:
            auth = InternalAuth()
        headers = {**auth.headers, "User-Agent": "git.sr.ht frontend"}
        if has_request_context():
            headers["X-Forwarded-For"] = ", ".join(request.access_route)
        if not client:
            backend_timeout = cfg("git.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) {
                  cursor
                  results {
                    ...repoDetails
                  }
                }
              }
            }

            fragment repoDetails on Repository {
              id
              name
              owner {
                __typename
                canonicalName
              }
            }
            """)
        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, name: str, **kwargs: Any) -> GetRepo:
        query = gql("""
            query GetRepo($name: String!) {
              me {
                repository(name: $name) {
                  ...repoDetails
                }
              }
            }

            fragment repoDetails on Repository {
              id
              name
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {"name": name}
        response = self.execute(
            query=query, operation_name="GetRepo", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetRepo.model_validate(data)

    def get_repo_access(self, owner: str, repo: str, **kwargs: Any) -> GetRepoAccess:
        query = gql("""
            query GetRepoAccess($owner: String!, $repo: String!) {
              user(username: $owner) {
                repository(name: $repo) {
                  access
                }
              }
            }
            """)
        variables: dict[str, object] = {"owner": owner, "repo": repo}
        response = self.execute(
            query=query, operation_name="GetRepoAccess", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetRepoAccess.model_validate(data)

    def get_references(
        self, name: str, cursor: Union[Optional[Any], UnsetType] = UNSET, **kwargs: Any
    ) -> GetReferences:
        query = gql("""
            query GetReferences($name: String!, $cursor: Cursor) {
              me {
                repository(name: $name) {
                  ...repoDetails
                  references(cursor: $cursor) {
                    cursor
                    results {
                      name
                    }
                  }
                }
              }
            }

            fragment repoDetails on Repository {
              id
              name
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {"name": name, "cursor": cursor}
        response = self.execute(
            query=query, operation_name="GetReferences", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetReferences.model_validate(data)

    def get_root_tree(self, name: str, ref: str, **kwargs: Any) -> GetRootTree:
        query = gql("""
            query GetRootTree($name: String!, $ref: String!) {
              me {
                repository(name: $name) {
                  ...repoDetails
                  reference(name: $ref) {
                    commit: follow {
                      __typename
                      ... on Commit {
                        ...commitDetails
                      }
                    }
                  }
                }
              }
            }

            fragment commitDetails on Commit {
              id
              message
              author {
                name
                email
                time
              }
            }

            fragment repoDetails on Repository {
              id
              name
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {"name": name, "ref": ref}
        response = self.execute(
            query=query, operation_name="GetRootTree", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetRootTree.model_validate(data)

    def get_tree(
        self, name: str, ref: str, branch: str, path: str, **kwargs: Any
    ) -> GetTree:
        query = gql("""
            query GetTree($name: String!, $ref: String!, $branch: String!, $path: String!) {
              me {
                repository(name: $name) {
                  ...repoDetails
                  path(revspec: $branch, path: $path) {
                    name
                    object {
                      __typename
                      id
                      type
                      ... on BinaryBlob {
                        content
                      }
                      ... on TextBlob {
                        text
                      }
                    }
                  }
                  reference(name: $ref) {
                    commit: follow {
                      __typename
                      ... on Commit {
                        ...commitDetails
                      }
                    }
                  }
                }
              }
            }

            fragment commitDetails on Commit {
              id
              message
              author {
                name
                email
                time
              }
            }

            fragment repoDetails on Repository {
              id
              name
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {
            "name": name,
            "ref": ref,
            "branch": branch,
            "path": path,
        }
        response = self.execute(
            query=query, operation_name="GetTree", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetTree.model_validate(data)

    def create_repo(
        self, name: str, visibility: Visibility, **kwargs: Any
    ) -> CreateRepo:
        query = gql("""
            mutation CreateRepo($name: String!, $visibility: Visibility!) {
              repository: createRepository(name: $name, visibility: $visibility) {
                id
                name
              }
            }
            """)
        variables: dict[str, object] = {"name": name, "visibility": visibility}
        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, id: int, **kwargs: Any) -> DeleteRepo:
        query = gql("""
            mutation DeleteRepo($id: Int!) {
              deleteRepository(id: $id) {
                id
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query, operation_name="DeleteRepo", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return DeleteRepo.model_validate(data)

    get_repos_query = "query GetRepos($cursor: Cursor) {\n  me {\n    repositories(cursor: $cursor) {\n      cursor\n      results {\n        ...repoDetails\n      }\n    }\n  }\n}"
    get_repo_query = "query GetRepo($name: String!) {\n  me {\n    repository(name: $name) {\n      ...repoDetails\n    }\n  }\n}"
    get_repo_access_query = "query GetRepoAccess($owner: String!, $repo: String!) {\n  user(username: $owner) {\n    repository(name: $repo) {\n      access\n    }\n  }\n}"
    get_references_query = "query GetReferences($name: String!, $cursor: Cursor) {\n  me {\n    repository(name: $name) {\n      ...repoDetails\n      references(cursor: $cursor) {\n        cursor\n        results {\n          name\n        }\n      }\n    }\n  }\n}"
    get_root_tree_query = "query GetRootTree($name: String!, $ref: String!) {\n  me {\n    repository(name: $name) {\n      ...repoDetails\n      reference(name: $ref) {\n        commit: follow {\n          __typename\n          ... on Commit {\n            ...commitDetails\n          }\n        }\n      }\n    }\n  }\n}"
    get_tree_query = "query GetTree($name: String!, $ref: String!, $branch: String!, $path: String!) {\n  me {\n    repository(name: $name) {\n      ...repoDetails\n      path(revspec: $branch, path: $path) {\n        name\n        object {\n          __typename\n          id\n          type\n          ... on BinaryBlob {\n            content\n          }\n          ... on TextBlob {\n            text\n          }\n        }\n      }\n      reference(name: $ref) {\n        commit: follow {\n          __typename\n          ... on Commit {\n            ...commitDetails\n          }\n        }\n      }\n    }\n  }\n}"
    create_repo_query = "mutation CreateRepo($name: String!, $visibility: Visibility!) {\n  repository: createRepository(name: $name, visibility: $visibility) {\n    id\n    name\n  }\n}"
    delete_repo_query = "mutation DeleteRepo($id: Int!) {\n  deleteRepository(id: $id) {\n    id\n  }\n}"
