import requests
import sys
from config import GEMINI_API_KEY, GEMINI_MODEL, WP_URL, WP_USERNAME, WP_APP_PASSWORD

def test_gemini():
    print("Testing Gemini API connection...")
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent?key={GEMINI_API_KEY}"
    headers = {"Content-Type": "application/json"}
    payload = {
        "contents": [{"parts": [{"text": "Hello, respond with the word 'Success' if you read this."}]}]
    }
    
    try:
        response = requests.post(url, headers=headers, json=payload, timeout=10)
        if response.status_code == 200:
            print("  [OK] Gemini API Connection Successful!")
            # Print response snippet
            res_json = response.json()
            reply = res_json["candidates"][0]["content"]["parts"][0]["text"].strip()
            print(f"  Gemini Response: '{reply}'")
            return True
        else:
            print(f"  [ERROR] Gemini API returned status code {response.status_code}")
            print(f"  Details: {response.text}")
            return False
    except Exception as e:
        print(f"  [ERROR] Failed to connect to Gemini: {e}")
        return False

def test_wordpress():
    print("\nTesting WordPress REST API connection...")
    # Clean URL and check system status or list posts
    clean_url = WP_URL.rstrip('/')
    url = f"{clean_url}/wp-json/wp/v2/users/me"
    auth = (WP_USERNAME, WP_APP_PASSWORD)
    
    try:
        response = requests.get(url, auth=auth, timeout=10)
        if response.status_code == 200:
            user_data = response.json()
            print("  [OK] WordPress Connection Successful!")
            print(f"  Logged in as: {user_data.get('name')} (Slug: {user_data.get('slug')}, Roles: {user_data.get('roles')})")
            return True
        elif response.status_code == 401:
            print("  [ERROR] WordPress authentication failed (401 Unauthorized).")
            print("  Please check that your WordPress Username and Application Password are correct.")
            return False
        else:
            print(f"  [ERROR] WordPress API returned status code {response.status_code}")
            print(f"  URL tested: {url}")
            print(f"  Details: {response.text}")
            return False
    except Exception as e:
        print(f"  [ERROR] Failed to connect to WordPress REST API: {e}")
        print(f"  Make sure your local site is running on XAMPP (Apache) and the URL '{clean_url}' is correct.")
        return False

if __name__ == "__main__":
    print("==================================================")
    print("Starting news automation API Diagnostics...")
    print("==================================================")
    
    gemini_ok = test_gemini()
    wp_ok = test_wordpress()
    
    print("\n==================================================")
    if gemini_ok and wp_ok:
        print("STATUS: SUCCESS! Your configurations are correct. You can now run main.py.")
    else:
        print("STATUS: FAILED. Please resolve the errors highlighted above before running main.py.")
    print("==================================================")
