#!/usr/bin/env python3
"""
Test script for Shopify GraphQL implementation
"""

import requests
import json
from datetime import datetime

def test_graphql_connection():
    """Test basic GraphQL connection to Shopify"""
    
    # Configuration
    SHOP_NAME = "odenthal"
    ACCESS_TOKEN = "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"
    API_VERSION = "2024-04"
    
    graphql_url = f"https://{SHOP_NAME}.myshopify.com/admin/api/{API_VERSION}/graphql.json"
    headers = {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": ACCESS_TOKEN
    }
    
    # Test query to get blogs
    query = """
    query {
      blogs(first: 5) {
        edges {
          node {
            id
            title
            handle
            url
          }
        }
      }
    }
    """
    
    print("🔍 Testing GraphQL connection to Shopify...")
    print(f"URL: {graphql_url}")
    print(f"Query: {query.strip()}")
    
    try:
        response = requests.post(
            graphql_url, 
            headers=headers, 
            json={"query": query}
        )
        
        print(f"Response Status: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print(f"Response Data: {json.dumps(data, indent=2)}")
            
            if 'errors' in data:
                print(f"❌ GraphQL Errors: {data['errors']}")
                return False
            elif 'data' in data and data['data']['blogs']['edges']:
                blogs = data['data']['blogs']['edges']
                print(f"✅ Successfully connected! Found {len(blogs)} blog(s):")
                for edge in blogs:
                    blog = edge['node']
                    print(f"  - {blog['title']} (ID: {blog['id']})")
                return True
            else:
                print("❌ No blogs found or unexpected response structure")
                return False
        else:
            print(f"❌ HTTP Error: {response.status_code}")
            print(f"Response: {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Exception: {e}")
        return False

def test_article_creation():
    """Test article creation with a simple example"""
    
    # Configuration
    SHOP_NAME = "odenthal"
    ACCESS_TOKEN = "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"
    API_VERSION = "2024-04"
    
    graphql_url = f"https://{SHOP_NAME}.myshopify.com/admin/api/{API_VERSION}/graphql.json"
    headers = {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": ACCESS_TOKEN
    }
    
    # First, get a blog ID
    blogs_query = """
    query {
      blogs(first: 1) {
        edges {
          node {
            id
            title
          }
        }
      }
    }
    """
    
    print("\n🔍 Getting blog ID for testing...")
    response = requests.post(graphql_url, headers=headers, json={"query": blogs_query})
    
    if response.status_code != 200:
        print(f"❌ Failed to get blogs: {response.status_code}")
        return False
    
    data = response.json()
    if 'errors' in data or not data['data']['blogs']['edges']:
        print(f"❌ No blogs available: {data}")
        return False
    
    blog_gid = data['data']['blogs']['edges'][0]['node']['id']
    blog_title = data['data']['blogs']['edges'][0]['node']['title']
    print(f"✅ Using blog: {blog_title} (GID: {blog_gid})")
    
    # Test article creation
    mutation = """
    mutation articleCreate($article: ArticleInput!) {
      articleCreate(article: $article) {
        article {
          id
          title
          author {
            name
          }
          handle
          publishedAt
        }
        userErrors {
          code
          field
          message
        }
      }
    }
    """
    
    article_input = {
        "blogId": blog_gid,
        "title": "Test Article from GraphQL API",
        "bodyHtml": "<h1>Test Article</h1><p>This is a test article created via GraphQL API.</p>",
        "author": "Test Author",
        "tags": ["Test", "GraphQL", "API"]
    }
    
    variables = {"article": article_input}
    
    print(f"\n🔍 Creating test article...")
    print(f"Article Input: {json.dumps(article_input, indent=2)}")
    
    response = requests.post(
        graphql_url, 
        headers=headers, 
        json={"query": mutation, "variables": variables}
    )
    
    print(f"Response Status: {response.status_code}")
    
    if response.status_code == 200:
        data = response.json()
        print(f"Response Data: {json.dumps(data, indent=2)}")
        
        if 'errors' in data:
            print(f"❌ GraphQL Errors: {data['errors']}")
            return False
        
        result = data['data']['articleCreate']
        
        if result['userErrors']:
            print(f"❌ User Errors: {result['userErrors']}")
            return False
        
        article = result['article']
        print(f"✅ Article created successfully!")
        print(f"  Title: {article['title']}")
        print(f"  ID: {article['id']}")
        print(f"  Handle: {article['handle']}")
        print(f"  Published: {article['publishedAt']}")
        return True
    else:
        print(f"❌ HTTP Error: {response.status_code}")
        print(f"Response: {response.text}")
        return False

if __name__ == "__main__":
    print("=== Shopify GraphQL API Test ===\n")
    
    # Test connection
    if test_graphql_connection():
        print("\n" + "="*50)
        # Test article creation
        test_article_creation()
    else:
        print("\n❌ GraphQL connection test failed. Please check your credentials and API version.")
