#!/usr/bin/env python3
"""
Simple test script for REST API functionality
"""

import requests
import json
from datetime import datetime

def test_rest_api():
    """Test REST API functionality"""
    
    SHOP_NAME = "odenthal"
    ACCESS_TOKEN = "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"
    API_VERSION = "2023-10"
    
    base_url = f"https://{SHOP_NAME}.myshopify.com/admin/api/{API_VERSION}"
    headers = {
        'X-Shopify-Access-Token': ACCESS_TOKEN,
        'Content-Type': 'application/json'
    }
    
    print("🔍 Testing REST API connection...")
    
    # Test 1: Get shop info
    shop_url = f"{base_url}/shop.json"
    try:
        response = requests.get(shop_url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            shop = data.get('shop', {})
            print(f"✅ Shop: {shop.get('name')} ({shop.get('domain')})")
        else:
            print(f"❌ Shop test failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Shop test exception: {e}")
        return False
    
    # Test 2: Get blogs
    blogs_url = f"{base_url}/blogs.json"
    try:
        response = requests.get(blogs_url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            blogs = data.get('blogs', [])
            print(f"✅ Found {len(blogs)} blogs:")
            for blog in blogs:
                print(f"  - {blog['title']} (ID: {blog['id']})")
            return blogs
        else:
            print(f"❌ Blogs test failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Blogs test exception: {e}")
        return False

def test_article_creation():
    """Test article creation"""
    
    SHOP_NAME = "odenthal"
    ACCESS_TOKEN = "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"
    API_VERSION = "2023-10"
    
    base_url = f"https://{SHOP_NAME}.myshopify.com/admin/api/{API_VERSION}"
    headers = {
        'X-Shopify-Access-Token': ACCESS_TOKEN,
        'Content-Type': 'application/json'
    }
    
    # First get blogs to find Tech Blogs
    blogs_url = f"{base_url}/blogs.json"
    response = requests.get(blogs_url, headers=headers)
    
    if response.status_code != 200:
        print("❌ Failed to get blogs for article test")
        return False
    
    blogs = response.json().get('blogs', [])
    tech_blog = None
    
    for blog in blogs:
        if blog['title'].lower() == 'tech blogs':
            tech_blog = blog
            break
    
    if not tech_blog:
        print("❌ Tech Blogs not found")
        return False
    
    print(f"✅ Found Tech Blogs (ID: {tech_blog['id']})")
    
    # Create test article
    article_url = f"{base_url}/blogs/{tech_blog['id']}/articles.json"
    
    article_data = {
        "article": {
            "title": "Test Article - REST API Working",
            "body_html": "<h1>Test Article</h1><p>This is a test article created via REST API.</p>",
            "author": "Test Author",
            "tags": "Test, REST API, Working",
            "published": True,
            "summary": "Testing REST API article creation"
        }
    }
    
    print("🔍 Creating test article...")
    response = requests.post(article_url, headers=headers, json=article_data)
    
    if response.status_code in [200, 201]:
        data = response.json()
        article = data.get('article', {})
        print(f"✅ Article created successfully!")
        print(f"  Title: {article.get('title')}")
        print(f"  ID: {article.get('id')}")
        print(f"  Status: {'Published' if article.get('published_at') else 'Draft'}")
        return True
    else:
        print(f"❌ Article creation failed: {response.status_code}")
        print(f"Response: {response.text}")
        return False

if __name__ == "__main__":
    print("=== REST API Test ===\n")
    
    blogs = test_rest_api()
    if blogs:
        print("\n" + "="*50)
        test_article_creation()
    else:
        print("\n❌ REST API test failed")
