#!/usr/bin/env python3
"""
Backend API Testing for inMotion Blog
Tests all backend APIs for the inMotion blog application
"""

import requests
import json
import sys
from datetime import datetime

# Backend URL from environment
BACKEND_URL = "https://seo-inmotion.preview.emergentagent.com/api"

class BlogAPITester:
    def __init__(self):
        self.base_url = BACKEND_URL
        self.session = requests.Session()
        self.test_results = []
        
    def log_test(self, test_name, success, message, response_data=None):
        """Log test results"""
        result = {
            "test": test_name,
            "success": success,
            "message": message,
            "timestamp": datetime.now().isoformat(),
            "response_data": response_data
        }
        self.test_results.append(result)
        status = "✅ PASS" if success else "❌ FAIL"
        print(f"{status} {test_name}: {message}")
        if response_data and not success:
            print(f"   Response: {response_data}")
    
    def test_api_root(self):
        """Test API root endpoint"""
        try:
            response = self.session.get(f"{self.base_url}/")
            if response.status_code == 200:
                data = response.json()
                if "message" in data and "inMotion" in data["message"]:
                    self.log_test("API Root", True, "API root endpoint working correctly", data)
                    return True
                else:
                    self.log_test("API Root", False, "API root response format incorrect", data)
                    return False
            else:
                self.log_test("API Root", False, f"API root returned status {response.status_code}", response.text)
                return False
        except Exception as e:
            self.log_test("API Root", False, f"API root connection failed: {str(e)}")
            return False
    
    def test_get_all_articles(self):
        """Test GET /api/articles - List all articles"""
        try:
            response = self.session.get(f"{self.base_url}/articles")
            if response.status_code == 200:
                articles = response.json()
                if isinstance(articles, list):
                    self.log_test("GET Articles", True, f"Retrieved {len(articles)} articles successfully")
                    return articles
                else:
                    self.log_test("GET Articles", False, "Articles response is not a list", articles)
                    return None
            else:
                self.log_test("GET Articles", False, f"GET articles failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Articles", False, f"GET articles request failed: {str(e)}")
            return None
    
    def test_get_featured_articles(self):
        """Test GET /api/articles/featured - Get featured articles"""
        try:
            response = self.session.get(f"{self.base_url}/articles/featured")
            if response.status_code == 200:
                articles = response.json()
                if isinstance(articles, list):
                    featured_count = len(articles)
                    # Verify all articles are actually featured
                    all_featured = all(article.get("featured", False) for article in articles)
                    if all_featured:
                        self.log_test("GET Featured Articles", True, f"Retrieved {featured_count} featured articles successfully")
                        return articles
                    else:
                        self.log_test("GET Featured Articles", False, "Some articles in featured list are not marked as featured")
                        return None
                else:
                    self.log_test("GET Featured Articles", False, "Featured articles response is not a list", articles)
                    return None
            else:
                self.log_test("GET Featured Articles", False, f"GET featured articles failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Featured Articles", False, f"GET featured articles request failed: {str(e)}")
            return None
    
    def test_get_article_by_slug(self, slug="beneficios-pilates-corpo-mente"):
        """Test GET /api/articles/:slug - Get article by slug"""
        try:
            response = self.session.get(f"{self.base_url}/articles/{slug}")
            if response.status_code == 200:
                article = response.json()
                if isinstance(article, dict) and "id" in article and "title" in article:
                    self.log_test("GET Article by Slug", True, f"Retrieved article '{article.get('title')}' by slug '{slug}'")
                    return article
                else:
                    self.log_test("GET Article by Slug", False, "Article response format incorrect", article)
                    return None
            elif response.status_code == 404:
                self.log_test("GET Article by Slug", False, f"Article with slug '{slug}' not found (404)")
                return None
            else:
                self.log_test("GET Article by Slug", False, f"GET article by slug failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Article by Slug", False, f"GET article by slug request failed: {str(e)}")
            return None
    
    def test_create_article(self):
        """Test POST /api/articles - Create new article"""
        test_article = {
            "title": "Artigo de Teste - Benefícios do Yoga",
            "slug": f"artigo-teste-yoga-{datetime.now().strftime('%Y%m%d%H%M%S')}",
            "excerpt": "Um artigo de teste sobre os benefícios do yoga para corpo e mente.",
            "content": "O yoga é uma prática milenar que oferece inúmeros benefícios para a saúde física e mental. Neste artigo, exploramos como a prática regular do yoga pode transformar sua vida.",
            "category": "Bem-estar",
            "tags": ["yoga", "saúde", "bem-estar", "exercício"],
            "imageUrl": "https://example.com/yoga-image.jpg",
            "featured": False
        }
        
        try:
            response = self.session.post(f"{self.base_url}/articles", json=test_article)
            if response.status_code == 200:
                created_article = response.json()
                if isinstance(created_article, dict) and "id" in created_article:
                    self.log_test("POST Create Article", True, f"Created article '{created_article.get('title')}' with ID {created_article.get('id')}")
                    return created_article
                else:
                    self.log_test("POST Create Article", False, "Created article response format incorrect", created_article)
                    return None
            else:
                self.log_test("POST Create Article", False, f"Create article failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("POST Create Article", False, f"Create article request failed: {str(e)}")
            return None
    
    def test_get_categories(self):
        """Test GET /api/categories - List categories"""
        try:
            response = self.session.get(f"{self.base_url}/categories")
            if response.status_code == 200:
                categories = response.json()
                if isinstance(categories, list):
                    self.log_test("GET Categories", True, f"Retrieved {len(categories)} categories successfully")
                    return categories
                else:
                    self.log_test("GET Categories", False, "Categories response is not a list", categories)
                    return None
            else:
                self.log_test("GET Categories", False, f"GET categories failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Categories", False, f"GET categories request failed: {str(e)}")
            return None
    
    def test_create_category(self):
        """Test POST /api/categories - Create category"""
        test_category = {
            "name": f"Categoria Teste {datetime.now().strftime('%H%M%S')}",
            "slug": f"categoria-teste-{datetime.now().strftime('%Y%m%d%H%M%S')}"
        }
        
        try:
            response = self.session.post(f"{self.base_url}/categories", json=test_category)
            if response.status_code == 200:
                created_category = response.json()
                if isinstance(created_category, dict) and "id" in created_category:
                    self.log_test("POST Create Category", True, f"Created category '{created_category.get('name')}' with ID {created_category.get('id')}")
                    return created_category
                else:
                    self.log_test("POST Create Category", False, "Created category response format incorrect", created_category)
                    return None
            else:
                self.log_test("POST Create Category", False, f"Create category failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("POST Create Category", False, f"Create category request failed: {str(e)}")
            return None
    
    def test_get_comments(self, article_id="1"):
        """Test GET /api/articles/:articleId/comments - Get comments"""
        try:
            response = self.session.get(f"{self.base_url}/articles/{article_id}/comments")
            if response.status_code == 200:
                comments = response.json()
                if isinstance(comments, list):
                    self.log_test("GET Comments", True, f"Retrieved {len(comments)} comments for article {article_id}")
                    return comments
                else:
                    self.log_test("GET Comments", False, "Comments response is not a list", comments)
                    return None
            else:
                self.log_test("GET Comments", False, f"GET comments failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Comments", False, f"GET comments request failed: {str(e)}")
            return None
    
    def test_create_comment(self, article_id="1"):
        """Test POST /api/articles/:articleId/comments - Create comment"""
        test_comment = {
            "author": "João Silva",
            "content": f"Este é um comentário de teste criado em {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}. Muito interessante este artigo!"
        }
        
        try:
            response = self.session.post(f"{self.base_url}/articles/{article_id}/comments", json=test_comment)
            if response.status_code == 200:
                created_comment = response.json()
                if isinstance(created_comment, dict) and "id" in created_comment:
                    self.log_test("POST Create Comment", True, f"Created comment by '{created_comment.get('author')}' for article {article_id}")
                    return created_comment
                else:
                    self.log_test("POST Create Comment", False, "Created comment response format incorrect", created_comment)
                    return None
            elif response.status_code == 404:
                self.log_test("POST Create Comment", False, f"Article {article_id} not found for comment creation")
                return None
            else:
                self.log_test("POST Create Comment", False, f"Create comment failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("POST Create Comment", False, f"Create comment request failed: {str(e)}")
            return None
    
    def test_create_contact_message(self):
        """Test POST /api/messages - Create contact message"""
        test_message = {
            "name": "Maria Santos",
            "email": "maria.santos@example.com",
            "message": f"Esta é uma mensagem de teste enviada em {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}. Gostaria de saber mais informações sobre os vossos serviços."
        }
        
        try:
            response = self.session.post(f"{self.base_url}/messages", json=test_message)
            if response.status_code == 200:
                created_message = response.json()
                if isinstance(created_message, dict) and "id" in created_message:
                    self.log_test("POST Create Message", True, f"Created contact message from '{created_message.get('name')}' ({created_message.get('email')})")
                    return created_message
                else:
                    self.log_test("POST Create Message", False, "Created message response format incorrect", created_message)
                    return None
            else:
                self.log_test("POST Create Message", False, f"Create message failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("POST Create Message", False, f"Create message request failed: {str(e)}")
            return None
    
    def test_get_messages(self):
        """Test GET /api/messages - List messages"""
        try:
            response = self.session.get(f"{self.base_url}/messages")
            if response.status_code == 200:
                messages = response.json()
                if isinstance(messages, list):
                    self.log_test("GET Messages", True, f"Retrieved {len(messages)} contact messages successfully")
                    return messages
                else:
                    self.log_test("GET Messages", False, "Messages response is not a list", messages)
                    return None
            else:
                self.log_test("GET Messages", False, f"GET messages failed with status {response.status_code}", response.text)
                return None
        except Exception as e:
            self.log_test("GET Messages", False, f"GET messages request failed: {str(e)}")
            return None
    
    def run_all_tests(self):
        """Run all backend API tests"""
        print("🚀 Starting inMotion Blog Backend API Tests")
        print("=" * 60)
        
        # Test API connectivity first
        if not self.test_api_root():
            print("❌ API connectivity failed. Stopping tests.")
            return False
        
        print("\n📝 Testing Articles APIs...")
        articles = self.test_get_all_articles()
        featured_articles = self.test_get_featured_articles()
        
        # Test article by slug
        article_by_slug = self.test_get_article_by_slug()
        
        # Test creating new article
        new_article = self.test_create_article()
        
        print("\n📂 Testing Categories APIs...")
        categories = self.test_get_categories()
        new_category = self.test_create_category()
        
        print("\n💬 Testing Comments APIs...")
        # First, try to get a real article ID from the articles we retrieved
        article_id_for_comments = "1"  # Default fallback
        if articles and len(articles) > 0:
            article_id_for_comments = articles[0].get("id", "1")
        
        comments = self.test_get_comments(article_id_for_comments)
        new_comment = self.test_create_comment(article_id_for_comments)
        
        print("\n📧 Testing Contact Messages APIs...")
        new_message = self.test_create_contact_message()
        messages = self.test_get_messages()
        
        # Summary
        print("\n" + "=" * 60)
        print("📊 TEST SUMMARY")
        print("=" * 60)
        
        total_tests = len(self.test_results)
        passed_tests = sum(1 for result in self.test_results if result["success"])
        failed_tests = total_tests - passed_tests
        
        print(f"Total Tests: {total_tests}")
        print(f"✅ Passed: {passed_tests}")
        print(f"❌ Failed: {failed_tests}")
        print(f"Success Rate: {(passed_tests/total_tests)*100:.1f}%")
        
        if failed_tests > 0:
            print("\n❌ FAILED TESTS:")
            for result in self.test_results:
                if not result["success"]:
                    print(f"  - {result['test']}: {result['message']}")
        
        return failed_tests == 0

if __name__ == "__main__":
    tester = BlogAPITester()
    success = tester.run_all_tests()
    sys.exit(0 if success else 1)