#!/usr/bin/env python3
"""
Complete cache cleaning utility for Sales Dashboard
Cleans Python cache, Flask cache, sessions, and browser instructions
"""

import os
import shutil
import json
from pathlib import Path
from datetime import datetime

def print_section(title):
    """Print formatted section header"""
    print("\n" + "="*70)
    print(f"  {title}")
    print("="*70)

def clean_python_cache():
    """Remove Python cache files (__pycache__, .pyc)"""
    print_section("CLEANING PYTHON CACHE")
    
    removed_count = 0
    
    # Find and remove __pycache__ directories
    for root, dirs, files in os.walk('.'):
        if '__pycache__' in dirs:
            pycache_path = os.path.join(root, '__pycache__')
            print(f"[*] Removing: {pycache_path}")
            try:
                shutil.rmtree(pycache_path)
                removed_count += 1
            except Exception as e:
                print(f"    ✗ Error: {e}")
    
    # Find and remove .pyc files
    for root, dirs, files in os.walk('.'):
        for file in files:
            if file.endswith('.pyc'):
                pyc_file = os.path.join(root, file)
                print(f"[*] Removing: {pyc_file}")
                try:
                    os.remove(pyc_file)
                    removed_count += 1
                except Exception as e:
                    print(f"    ✗ Error: {e}")
    
    if removed_count > 0:
        print(f"\n✓ Cleaned {removed_count} Python cache items")
    else:
        print("\n✓ No Python cache found (already clean)")
    
    return removed_count > 0

def clean_flask_sessions():
    """Clear Flask session data"""
    print_section("CLEANING FLASK SESSION DATA")
    
    # Sessions are typically in-memory in Flask-Login
    # But we can clear any persistent session files if they exist
    
    session_dirs = [
        'flask_session',
        'sessions',
        'cache',
        'tmp'
    ]
    
    removed = 0
    for session_dir in session_dirs:
        if os.path.exists(session_dir):
            print(f"[*] Removing: {session_dir}/")
            try:
                shutil.rmtree(session_dir)
                removed += 1
            except Exception as e:
                print(f"    ✗ Error: {e}")
    
    if removed > 0:
        print(f"\n✓ Cleaned {removed} session directories")
    else:
        print("\n✓ No session directories found (already clean)")
    
    return removed > 0

def clean_compiled_assets():
    """Clean compiled assets and temporary files"""
    print_section("CLEANING COMPILED ASSETS")
    
    patterns_to_clean = [
        '*.pyc',
        '*.pyo',
        '*.pyd',
        '.DS_Store',
        '*.egg-info',
        'dist',
        'build'
    ]
    
    removed = 0
    
    for pattern in patterns_to_clean:
        if '*' in pattern:
            # Handle wildcard patterns
            for root, dirs, files in os.walk('.'):
                for file in files:
                    if file.endswith(pattern.replace('*', '')):
                        file_path = os.path.join(root, file)
                        try:
                            os.remove(file_path)
                            print(f"[*] Removed: {file_path}")
                            removed += 1
                        except:
                            pass
        else:
            # Handle directory patterns
            if os.path.isdir(pattern):
                try:
                    shutil.rmtree(pattern)
                    print(f"[*] Removed: {pattern}/")
                    removed += 1
                except:
                    pass
    
    if removed > 0:
        print(f"\n✓ Cleaned {removed} asset files")
    else:
        print("\n✓ No compiled assets found")
    
    return removed > 0

def show_browser_cache_instructions():
    """Display browser cache cleaning instructions"""
    print_section("BROWSER CACHE - MANUAL CLEANUP REQUIRED")
    
    print("\nBrowser-specific cache cleaning:\n")
    
    browsers = {
        "Chrome": "Ctrl+Shift+Delete → 'All time' → 'Cached images' + 'Cookies and site data' → Clear",
        "Edge": "Ctrl+Shift+Delete → 'All time' → 'Cached images' + 'Cookies and site data' → Clear",
        "Firefox": "Ctrl+Shift+Delete → 'Everything' → Clear Now",
        "Safari": "Develop → Empty Web Caches (or Safari → Settings → Advanced → Show Develop menu)",
        "Opera": "Ctrl+Shift+Delete → 'All time' → 'Cached images' + 'Cookies' → Clear",
    }
    
    for browser, steps in browsers.items():
        print(f"  {browser}:")
        print(f"    {steps}\n")
    
    print("\n  OR use hard refresh:")
    print("    Windows/Linux: Ctrl+F5 or Ctrl+Shift+R")
    print("    Mac: Cmd+Shift+R")

def show_network_analysis():
    """Show how to use browser DevTools to analyze network issues"""
    print_section("NETWORK TROUBLESHOOTING - BROWSER DEVTOOLS")
    
    print("\nTo diagnose ngrok/network issues:\n")
    print("  1. Open your ngrok URL in browser")
    print("  2. Press F12 to open DevTools")
    print("  3. Go to 'Network' tab")
    print("  4. Reload the page (F5)")
    print("  5. Look for red/failed requests")
    print("\nCommon issues:")
    print("  • 'ERR_NGROK_3200' = Connection timeout/network issue")
    print("  • '403' = Forbidden/not authenticated")
    print("  • '502' = Bad Gateway (Flask not responding)")
    print("  • '504' = Gateway Timeout (ngrok tunnel issue)")

def check_and_display_cache_info():
    """Display current cache information"""
    print_section("CACHE STATUS REPORT")
    
    cache_items = {
        '__pycache__': 0,
        '.pyc files': 0,
        'Session files': 0,
        'Temp files': 0
    }
    
    # Count __pycache__
    for root, dirs, files in os.walk('.'):
        if '__pycache__' in dirs:
            cache_items['__pycache__'] += 1
        cache_items['.pyc files'] += len([f for f in files if f.endswith('.pyc')])
        cache_items['Temp files'] += len([f for f in files if f.endswith('.tmp')])
    
    print("\nCurrent cache summary:")
    for cache_type, count in cache_items.items():
        status = "✓" if count == 0 else "✗"
        print(f"  {status} {cache_type}: {count}")

def main():
    print("\n" + "="*70)
    print("  SALES DASHBOARD - COMPLETE CACHE CLEANER")
    print("="*70)
    print(f"\n  Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Display current status
    check_and_display_cache_info()
    
    # Clean caches
    print("\n" + "-"*70 + "\nCLEANING IN PROGRESS...\n" + "-"*70)
    
    python_cleaned = clean_python_cache()
    sessions_cleaned = clean_flask_sessions()
    assets_cleaned = clean_compiled_assets()
    
    # Show browser instructions
    show_browser_cache_instructions()
    show_network_analysis()
    
    # Summary
    print_section("CLEANUP COMPLETE")
    
    print("\n✓ Local cache cleanup finished!")
    print("\nTo fully resolve cache issues:")
    print("  1. Follow browser cache clearing instructions above")
    print("  2. Restart Flask: python app.py")
    print("  3. Hard refresh ngrok URL: Ctrl+shift+R (Windows) or Cmd+Shift+R (Mac)")
    print("  4. Try logging in again")
    
    print("\n" + "="*70 + "\n")

if __name__ == '__main__':
    main()
