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

import os
import csv
import sys
import tempfile
from datetime import datetime

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

from social_agent import SocialMediaPoster


class TestCSVLogging:
    """Test class for CSV logging functionality"""
    
    def __init__(self):
        self.test_results = []
        self.temp_csv_file = None
        
    def setup_test_environment(self):
        """Setup test environment with temporary CSV file"""
        try:
            # Create a temporary CSV file for testing
            self.temp_csv_file = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False)
            self.temp_csv_file.close()
            
            # Create a test instance with custom CSV file
            self.poster = SocialMediaPoster()
            self.poster.successful_posts_csv = self.temp_csv_file.name
            
            # Ensure CSV headers are created
            self.poster._ensure_csv_headers()
            
            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_file_creation(self):
        """Test that CSV file is created with proper headers"""
        try:
            if not os.path.exists(self.poster.successful_posts_csv):
                self.test_results.append(("CSV File Creation", False, "CSV file was not created"))
                return False
            
            # Check if file has proper headers
            with open(self.poster.successful_posts_csv, 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                first_row = next(reader, None)
                
                expected_headers = ['timestamp', 'platform', 'post_type', 'content', 'post_id']
                if first_row == expected_headers:
                    self.test_results.append(("CSV File Creation", True, "CSV file created with proper headers"))
                    return True
                else:
                    self.test_results.append(("CSV File Creation", False, f"Headers mismatch. Expected: {expected_headers}, Got: {first_row}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("CSV File Creation", False, f"Exception: {e}"))
            return False
    
    def test_single_post_logging(self):
        """Test logging a single successful post"""
        try:
            test_content = "This is a test post for CSV logging functionality."
            test_post_id = "1234567890"
            
            # Log a successful post
            self.poster.log_successful_post("twitter", "social", test_content, test_post_id)
            
            # Verify the post was logged
            with open(self.poster.successful_posts_csv, 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                rows = list(reader)
                
                # Should have header + 1 data row
                if len(rows) == 2:
                    data_row = rows[1]
                    if (data_row[1] == "twitter" and 
                        data_row[2] == "social" and 
                        data_row[4] == test_post_id):
                        self.test_results.append(("Single Post Logging", True, "Post logged successfully"))
                        return True
                    else:
                        self.test_results.append(("Single Post Logging", False, f"Data mismatch: {data_row}"))
                        return False
                else:
                    self.test_results.append(("Single Post Logging", False, f"Expected 2 rows, got {len(rows)}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("Single Post Logging", False, f"Exception: {e}"))
            return False
    
    def test_multiple_posts_logging(self):
        """Test logging multiple posts with different types"""
        try:
            test_posts = [
                ("facebook", "fact", "This is a test fact post", "9876543210"),
                ("twitter", "joke", "Why did the chicken cross the road? To get to the other side! 😄", "5555555555"),
                ("facebook", "social", "Regular social media post content", "1111111111")
            ]
            
            # Log multiple posts
            for platform, post_type, content, post_id in test_posts:
                self.poster.log_successful_post(platform, post_type, content, post_id)
            
            # Verify all posts were logged
            with open(self.poster.successful_posts_csv, 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                rows = list(reader)
                
                # Should have header + 4 data rows (1 from previous test + 3 new ones)
                if len(rows) == 5:
                    # Check the last 3 rows (new posts)
                    for i, (platform, post_type, content, post_id) in enumerate(test_posts):
                        data_row = rows[i + 2]  # Skip header and first test row
                        if (data_row[1] == platform and 
                            data_row[2] == post_type and 
                            data_row[4] == post_id):
                            continue
                        else:
                            self.test_results.append(("Multiple Posts Logging", False, f"Post {i+1} data mismatch: {data_row}"))
                            return False
                    
                    self.test_results.append(("Multiple Posts Logging", True, "All posts logged successfully"))
                    return True
                else:
                    self.test_results.append(("Multiple Posts Logging", False, f"Expected 5 rows, got {len(rows)}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("Multiple Posts Logging", False, f"Exception: {e}"))
            return False
    
    def test_content_truncation(self):
        """Test that long content is properly truncated"""
        try:
            # Create a very long content string
            long_content = "A" * 300  # 300 characters
            test_post_id = "9999999999"
            
            # Log the long content
            self.poster.log_successful_post("twitter", "social", long_content, test_post_id)
            
            # Verify content was truncated
            with open(self.poster.successful_posts_csv, 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                rows = list(reader)
                
                # Get the last row
                last_row = rows[-1]
                logged_content = last_row[3]
                
                # Should be truncated to 200 chars + "..."
                if len(logged_content) == 203 and logged_content.endswith("..."):
                    self.test_results.append(("Content Truncation", True, "Long content properly truncated"))
                    return True
                else:
                    self.test_results.append(("Content Truncation", False, f"Content not properly truncated. Length: {len(logged_content)}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("Content Truncation", False, f"Exception: {e}"))
            return False
    
    def test_content_cleaning(self):
        """Test that content is properly cleaned for CSV format"""
        try:
            # Content with newlines and quotes
            messy_content = 'This is a "test" post\nwith newlines\r\nand quotes'
            test_post_id = "8888888888"
            
            # Log the messy content
            self.poster.log_successful_post("facebook", "social", messy_content, test_post_id)
            
            # Verify content was cleaned
            with open(self.poster.successful_posts_csv, 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                rows = list(reader)
                
                # Get the last row
                last_row = rows[-1]
                logged_content = last_row[3]
                
                # Should not contain newlines or double quotes
                if '\n' not in logged_content and '\r' not in logged_content and '"' not in logged_content:
                    self.test_results.append(("Content Cleaning", True, "Content properly cleaned for CSV"))
                    return True
                else:
                    self.test_results.append(("Content Cleaning", False, f"Content not properly cleaned: {logged_content}"))
                    return False
                    
        except Exception as e:
            self.test_results.append(("Content Cleaning", False, f"Exception: {e}"))
            return False
    
    def run_all_tests(self):
        """Run all CSV logging tests"""
        print("\n" + "="*60)
        print("🧪 RUNNING CSV LOGGING 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_file_creation,
                self.test_single_post_logging,
                self.test_multiple_posts_logging,
                self.test_content_truncation,
                self.test_content_cleaning
            ]
            
            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("📊 CSV LOGGING 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_csv_logging_tests():
    """Main function to run CSV logging tests"""
    tester = TestCSVLogging()
    return tester.run_all_tests()


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