#!/usr/bin/env python3
"""
Test script to verify brand analysis cache functionality
"""

import os
import sys
import json
import tempfile
import shutil
from unittest.mock import patch

# Add parent directory to Python path for imports
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from loki.loki_qwen import BrandAnalysisService, LokiConfig

def test_cache_file_path_generation():
    """Test that cache file path is generated correctly"""
    print("🧪 Testing cache file path generation...")
    
    # Create a test config
    config = LokiConfig()
    config.brand_analysis_url = "https://test-store.myshopify.com"
    
    # Create service instance
    service = BrandAnalysisService(config)
    
    # Check that cache file path is correctly generated
    expected_path = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        "databases", "brands", "brand_analysis_test-store.myshopify.com.json"
    )
    
    assert service.cache_file == expected_path, f"Expected {expected_path}, got {service.cache_file}"
    print(f"✅ Cache file path correctly generated: {service.cache_file}")
    
    # Check that directories are created
    brands_dir = os.path.dirname(service.cache_file)
    assert os.path.exists(brands_dir), f"Brands directory should exist: {brands_dir}"
    print(f"✅ Brands directory created: {brands_dir}")

def test_cache_save_and_load():
    """Test that cache can be saved and loaded correctly"""
    print("🧪 Testing cache save and load functionality...")
    
    # Create a test config
    config = LokiConfig()
    config.brand_analysis_url = "https://test-store.myshopify.com"
    
    # Create service instance
    service = BrandAnalysisService(config)
    
    # Test data
    test_analysis_data = {
        "website_url": "https://test-store.myshopify.com",
        "pages_analyzed": 5,
        "analysis_method": "AI-powered",
        "brand_analysis": {
            "what_brand_represents": "Test brand analysis",
            "target_audience": "Test audience",
            "typical_buyers": "Test buyers",
            "emotional_impact": "Test impact",
            "sales_drivers": "Test drivers"
        },
        "blog_topics": {
            "EDUCATIONAL CONTENT": ["Topic 1", "Topic 2"],
            "INDUSTRY INSIGHTS": ["Topic 3", "Topic 4"],
            "BRAND STORIES": ["Topic 5", "Topic 6"]
        }
    }
    
    # Save cache
    service.save_analysis_cache(test_analysis_data)
    print(f"✅ Cache saved to: {service.cache_file}")
    
    # Verify file exists
    assert os.path.exists(service.cache_file), f"Cache file should exist: {service.cache_file}"
    
    # Load cache
    loaded_data = service.load_cached_analysis()
    assert loaded_data is not None, "Loaded data should not be None"
    
    # Verify data integrity
    assert loaded_data["website_url"] == test_analysis_data["website_url"]
    assert loaded_data["pages_analyzed"] == test_analysis_data["pages_analyzed"]
    assert loaded_data["analysis_method"] == test_analysis_data["analysis_method"]
    print("✅ Cache data integrity verified")

def test_different_domains():
    """Test that different domains generate different cache files"""
    print("🧪 Testing different domain cache file generation...")
    
    test_urls = [
        "https://store1.myshopify.com",
        "https://store2.myshopify.com", 
        "https://example.com",
        "https://test-store.shopify.com"
    ]
    
    cache_files = []
    for url in test_urls:
        config = LokiConfig()
        config.brand_analysis_url = url
        service = BrandAnalysisService(config)
        cache_files.append(service.cache_file)
        print(f"✅ URL: {url} -> Cache: {service.cache_file}")
    
    # Verify all cache files are unique
    assert len(set(cache_files)) == len(cache_files), "All cache files should be unique"
    print("✅ All cache files are unique for different domains")

def cleanup_test_files():
    """Clean up test files"""
    print("🧹 Cleaning up test files...")
    
    # Remove test cache files
    test_domains = ["test-store.myshopify.com", "store1.myshopify.com", "store2.myshopify.com", "example.com", "test-store.shopify.com"]
    
    brands_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "databases", "brands")
    
    for domain in test_domains:
        cache_file = os.path.join(brands_dir, f"brand_analysis_{domain}.json")
        if os.path.exists(cache_file):
            os.remove(cache_file)
            print(f"🗑️ Removed test cache file: {cache_file}")

def main():
    """Run all tests"""
    print("🚀 Starting brand analysis cache tests...")
    print("=" * 60)
    
    try:
        test_cache_file_path_generation()
        print()
        
        test_cache_save_and_load()
        print()
        
        test_different_domains()
        print()
        
        print("=" * 60)
        print("✅ All tests passed successfully!")
        
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return 1
    
    finally:
        cleanup_test_files()
    
    return 0

if __name__ == "__main__":
    exit(main())
