import gql
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport

from configs.firebase import db
from constants.collections import SHOPS_CREDENTIALS_COLLECTION
from V2.functions.Shops.main import Shop

SHOPIFY_API_VERSION = "2025-01"
import json

import requests


class ShopifyGraphQLClient:
    def __init__(self, shop:Shop):
        """
        Initialize the Shopify GraphQL Client.
        
        :param shop_url: Your Shopify store URL (e.g., 'your-store.myshopify.com')
        :param access_token: The Shopify access token
        """
        self.endpoint = f"{shop.url}/admin/api/{SHOPIFY_API_VERSION}/graphql.json"
        self.headers = {
            "Content-Type": "application/json",
            "X-Shopify-Access-Token": shop.accessToken
        }
        self.id = shop.id
        self.shop = shop

    def execute(self, query,  variables=None):
        """
        Execute a GraphQL query or mutation.

        :param operation_type: The type of operation ("query" or "mutation")
        :param operation_name: The name of the GraphQL operation (e.g., "products", "productCreate")
        :param input_data: A dictionary of input data for mutations (optional)
        :param fields: A string specifying the fields to return in the response
        :param variables: A dictionary of variables for the query/mutation (optional)
        :return: Parsed JSON response from Shopify
        """
        # Validate operation type
        # if operation_type not in ["query", "mutation"]:
        #     raise ValueError("Operation type must be 'query' or 'mutation'.")

        # Build the GraphQL query/mutation
        # if operation_type == "mutation":
        #     # For mutations, include the input data
        #     query = f"""
        #     {operation_type} ($input: {input_name}!) {{
        #         {operation_name}(input: $input) {{
        #             {fields or "userErrors { field message }"}
        #         }}
        #     }}
        #     """
        # else:
        #     # For queries, no input data is required
        # query = f"""
        #     {query}
        # """

        # Prepare the payload
        payload = {
            "query": query,
            "variables": variables or {}
        }

        # Execute the request
        response = requests.post(self.endpoint, headers=self.headers, json=payload)

        # Raise exception for non-200 status codes
        if response.status_code != 200:
            raise Exception(f"GraphQL request failed: {response.status_code} {response.text}")

        # Parse and return the response
        return response.json()
    

def getShopifyShopByDomain(domain:str) -> Shop|None:
    """
    Get a Shopify shop by its domain.
    """
    query = db.collection(SHOPS_CREDENTIALS_COLLECTION).where("platformId", "==", "2").where("url", "==", domain).get()
    if query: return Shop.from_dict(query[0].to_dict())

import re


def shopifyNumId(gid: str) -> str:
    """
    Convert a Shopify Global ID (GID) to its numeric ID.

    :param gid: Shopify GID (e.g., "gid://shopify/Product/1234567890")
    :return: Extracted numeric ID as a string
    """
    match = re.search(r'(\d+)$', gid)
    return match.group(1) if match else None


def shopifyGid(id: str, type: str) -> str:
    """
    Convert a numeric Shopify ID to a Shopify Global ID (GID).

    :param numeric_id: The numeric ID (e.g., "1234567890")
    :param type: The Shopify resource type (e.g., "Product", "ProductVariant", "Order")
    :return: Shopify GID (e.g., "gid://shopify/Product/1234567890")
    """
    return f"gid://shopify/{type}/{id}"


import re
from urllib.parse import urlparse


def validate_shopify_id(shopify_id: str, resource_type: str) -> str:
    """
    Validate if the given Shopify ID is a GID or a numeric ID.
    If numeric, convert it to a valid Shopify GID.
    Also, removes any query parameters like '?id=true'.

    :param shopify_id: The ID to check (either GID or numeric ID)
    :param resource_type: The Shopify resource type (e.g., "Product", "ProductVariant", "Order", etc.)
    :return: The correct Shopify GID
    """
    # Remove any query parameters (e.g., ?id=true)
    shopify_id = urlparse(shopify_id).path  # Extract only the main part of the URL

    gid_pattern = rf"^gid://shopify/{resource_type}/\d+$"

    if re.match(gid_pattern, shopify_id):  # ✅ Already a valid GID
        return shopify_id
    elif shopify_id.isdigit():  # ✅ Numeric ID, convert to GID
        return f"gid://shopify/{resource_type}/{shopify_id}"
    return shopify_id