#!/usr/bin/env python3
"""
Test suite for posting functionality
"""

import os
import sys
import tempfile
import csv
from unittest.mock import patch, MagicMock

# Add parent directory to path to import modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from social_agent import SocialMediaPoster


class TestPostingFunctionality:
    """Test class for posting functionality"""
    
    def __init__(self):
        self.test_results = []
        self.temp_csv_file = None
        
    def setup_test_environment(self):
        """Setup test environment with mock data"""
        try:
            # Create a temporary CSV file for testing
            self.temp_csv_file = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False)
            
            # Write test data to CSV
            test_posts = [
                {'content': 'Test post 1', 'twitter_post': 'Test post 1'},
                {'content': 'Test post 2', 'twitter_post': 'Test post 2'},
                {'content': 'Test post 3', 'twitter_post': 'Test post 3'}
            ]
            
            fieldnames = ['content', 'twitter_post']
            writer = csv.DictWriter(self.temp_csv_file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(test_posts)
            self.temp_csv_file.close()
            
            # Create a test instance
            self.poster = SocialMediaPoster()
            
            print("✅ Test environment setup completed")
            return True
            
        except Exception as e:
            print(f"❌ Failed to setup test environment: {e}")
            return False
    
    def cleanup_test_environment(self):
        """Cleanup test environment"""
        try:
            if self.temp_csv_file and os.path.exists(self.temp_csv_file.name):
                os.unlink(self.temp_csv_file.name)
            print("✅ Test environment cleaned up")
        except Exception as e:
            print(f"⚠️ Warning: Failed to cleanup test environment: {e}")
    
    def test_csv_reading(self):
        """Test reading posts from CSV file"""
        try:
            posts = self.poster.read_csv_posts(self.temp_csv_file.name)
            
            if len(posts) == 3:
                # Check if posts have expected structure
                first_post = posts[0]
                if 'content' in first_post and 'twitter_post' in first_post:
                    self.test_results.append(("CSV Reading", True, f"Successfully read {len(posts)} posts from CSV"))
                    return True
                else:
                    self.test_results.append(("CSV Reading", False, f"Posts missing expected fields: {list(first_post.keys())}"))
                    return False
            else:
                self.test_results.append(("CSV Reading", False, f"Expected 3 posts, got {len(posts)}"))
                return False
                
        except Exception as e:
            self.test_results.append(("CSV Reading", False, f"Exception: {e}"))
            return False
    
    def test_random_post_selection(self):
        """Test random post selection"""
        try:
            posts = self.poster.read_csv_posts(self.temp_csv_file.name)
            
            # Test multiple selections to ensure randomness
            selected_posts = []
            for _ in range(10):
                selected_post = self.poster.get_random_post(posts)
                selected_posts.append(selected_post['content'])
            
            # Should get different posts (not guaranteed but very likely with 3 posts and 10 selections)
            unique_posts = set(selected_posts)
            if len(unique_posts) > 1:
                self.test_results.append(("Random Post Selection", True, f"Selected {len(unique_posts)} unique posts from {len(selected_posts)} selections"))
                return True
            else:
                self.test_results.append(("Random Post Selection", False, "All selections returned the same post (possible but unlikely)"))
                return False
                
        except Exception as e:
            self.test_results.append(("Random Post Selection", False, f"Exception: {e}"))
            return False
    
    def test_url_extraction(self):
        """Test URL extraction from content"""
        try:
            test_content = "Check out this link: https://example.com and this one: http://test.org"
            urls = self.poster.extract_urls_from_content(test_content)
            
            expected_urls = ["https://example.com", "http://test.org"]
            if urls == expected_urls:
                self.test_results.append(("URL Extraction", True, f"Successfully extracted {len(urls)} URLs"))
                return True
            else:
                self.test_results.append(("URL Extraction", False, f"Expected {expected_urls}, got {urls}"))
                return False
                
        except Exception as e:
            self.test_results.append(("URL Extraction", False, f"Exception: {e}"))
            return False
    
    def test_url_validation(self):
        """Test URL validation"""
        try:
            # Test valid URL
            valid_url = "https://www.google.com"
            is_valid = self.poster.validate_url(valid_url)
            
            # Test invalid URL
            invalid_url = "https://thisurldoesnotexist12345.com"
            is_invalid = self.poster.validate_url(invalid_url)
            
            # Valid URL should return True, invalid should return False
            if is_valid and not is_invalid:
                self.test_results.append(("URL Validation", True, "URL validation working correctly"))
                return True
            else:
                self.test_results.append(("URL Validation", False, f"Valid URL: {is_valid}, Invalid URL: {is_invalid}"))
                return False
                
        except Exception as e:
            self.test_results.append(("URL Validation", False, f"Exception: {e}"))
            return False
    
    def test_content_preparation(self):
        """Test content preparation for different platforms"""
        try:
            test_content = "Check out this link: https://example.com"
            
            # Test Twitter content preparation
            twitter_content = self.poster.prepare_content_with_links(test_content, "twitter")
            
            # Test Facebook content preparation
            facebook_content = self.poster.prepare_content_with_links(test_content, "facebook")
            
            # Both should contain the URL
            if "https://example.com" in twitter_content and "https://example.com" in facebook_content:
                self.test_results.append(("Content Preparation", True, "Content prepared correctly for both platforms"))
                return True
            else:
                self.test_results.append(("Content Preparation", False, f"Twitter: {twitter_content}, Facebook: {facebook_content}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Content Preparation", False, f"Exception: {e}"))
            return False
    
    def test_duplicate_error_detection(self):
        """Test duplicate error detection"""
        try:
            # Test Twitter duplicate detection
            twitter_error = Exception("Status is a duplicate of another Tweet")
            is_twitter_duplicate = self.poster.is_duplicate_error(twitter_error, "twitter")
            
            # Test Facebook duplicate detection
            facebook_error = Exception("This message is identical to a previous post")
            is_facebook_duplicate = self.poster.is_duplicate_error(facebook_error, "facebook")
            
            # Test non-duplicate error
            normal_error = Exception("Some other error")
            is_normal_duplicate = self.poster.is_duplicate_error(normal_error, "twitter")
            
            if is_twitter_duplicate and is_facebook_duplicate and not is_normal_duplicate:
                self.test_results.append(("Duplicate Error Detection", True, "Duplicate error detection working correctly"))
                return True
            else:
                self.test_results.append(("Duplicate Error Detection", False, f"Twitter: {is_twitter_duplicate}, Facebook: {is_facebook_duplicate}, Normal: {is_normal_duplicate}"))
                return False
                
        except Exception as e:
            self.test_results.append(("Duplicate Error Detection", False, f"Exception: {e}"))
            return False
    
    def test_scheduler_setup(self):
        """Test scheduler setup functionality"""
        try:
            # Test scheduler setup
            self.poster.setup_scheduler(
                self.temp_csv_file.name,
                "twitter_post",
                ["06:00", "12:00"],
                ["08:00"],
                ["15:00"]
            )
            
            # Check if jobs were created
            import schedule
            jobs = schedule.get_jobs()
            
            if len(jobs) > 0:
                self.test_results.append(("Scheduler Setup", True, f"Successfully created {len(jobs)} scheduled jobs"))
                return True
            else:
                self.test_results.append(("Scheduler Setup", False, "No jobs were created"))
                return False
                
        except Exception as e:
            self.test_results.append(("Scheduler Setup", False, f"Exception: {e}"))
            return False
        finally:
            # Clear schedule for next tests
            import schedule
            schedule.clear()
    
    def run_all_tests(self):
        """Run all posting functionality tests"""
        print("\n" + "="*60)
        print("📤 RUNNING POSTING FUNCTIONALITY TESTS")
        print("="*60)
        
        # Setup test environment
        if not self.setup_test_environment():
            print("❌ Failed to setup test environment. Aborting tests.")
            return False
        
        try:
            # Run all tests
            tests = [
                self.test_csv_reading,
                self.test_random_post_selection,
                self.test_url_extraction,
                self.test_url_validation,
                self.test_content_preparation,
                self.test_duplicate_error_detection,
                self.test_scheduler_setup
            ]
            
            passed = 0
            total = len(tests)
            
            for test in tests:
                print(f"\n🔍 Running {test.__name__}...")
                if test():
                    passed += 1
                    print(f"✅ {test.__name__} PASSED")
                else:
                    print(f"❌ {test.__name__} FAILED")
            
            # Print summary
            print("\n" + "="*60)
            print("📊 POSTING FUNCTIONALITY TEST SUMMARY")
            print("="*60)
            print(f"Total Tests: {total}")
            print(f"Passed: {passed}")
            print(f"Failed: {total - passed}")
            print(f"Success Rate: {(passed/total)*100:.1f}%")
            
            # Print detailed results
            print("\n📋 Detailed Results:")
            for test_name, success, message in self.test_results:
                status = "✅ PASS" if success else "❌ FAIL"
                print(f"  {status} {test_name}: {message}")
            
            return passed == total
            
        finally:
            self.cleanup_test_environment()


def run_posting_functionality_tests():
    """Main function to run posting functionality tests"""
    tester = TestPostingFunctionality()
    return tester.run_all_tests()


if __name__ == "__main__":
    success = run_posting_functionality_tests()
    exit(0 if success else 1)