#!/usr/bin/env python3
"""
Clean database script - removes all data from KPI Analysis database
Use this to start fresh after testing
"""

import sqlite3
import os
import shutil
from pathlib import Path

def clean_database():
    """Clean all data from the database"""
    db_path = Path("data/kpi_analysis.db")
    
    if not db_path.exists():
        print(f"❌ Database not found at {db_path}")
        return False
    
    print(f"🗑️  Cleaning database: {db_path}")
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Get table names
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = cursor.fetchall()
        
        print(f"\n📊 Found {len(tables)} tables")
        
        # Delete data from each table
        for table in tables:
            table_name = table[0]
            if table_name != 'sqlite_sequence':  # Skip internal table
                cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
                count = cursor.fetchone()[0]
                
                if count > 0:
                    print(f"   Deleting {count} rows from {table_name}...")
                    cursor.execute(f"DELETE FROM {table_name}")
                else:
                    print(f"   {table_name} is already empty")
        
        # Reset auto-increment counters
        cursor.execute("DELETE FROM sqlite_sequence")
        
        conn.commit()
        conn.close()
        
        print("\n✅ Database cleaned successfully!")
        return True
        
    except Exception as e:
        print(f"\n❌ Error cleaning database: {e}")
        return False

def clean_uploads():
    """Clean uploaded files"""
    uploads_dir = Path("uploads")
    
    if not uploads_dir.exists():
        print(f"\n📁 Uploads directory not found at {uploads_dir}")
        return
    
    files = list(uploads_dir.glob("*"))
    if not files:
        print(f"\n📁 Uploads directory is already empty")
        return
    
    print(f"\n🗑️  Cleaning uploads directory: {uploads_dir}")
    print(f"   Found {len(files)} files")
    
    for file in files:
        if file.is_file():
            try:
                file.unlink()
                print(f"   Deleted: {file.name}")
            except Exception as e:
                print(f"   ❌ Failed to delete {file.name}: {e}")

def clean_reports():
    """Clean generated reports"""
    reports_dir = Path("reports")
    
    if not reports_dir.exists():
        print(f"\n📄 Reports directory not found at {reports_dir}")
        return
    
    files = list(reports_dir.glob("*"))
    if not files:
        print(f"\n📄 Reports directory is already empty")
        return
    
    print(f"\n🗑️  Cleaning reports directory: {reports_dir}")
    print(f"   Found {len(files)} files")
    
    for file in files:
        if file.is_file():
            try:
                file.unlink()
                print(f"   Deleted: {file.name}")
            except Exception as e:
                print(f"   ❌ Failed to delete {file.name}: {e}")

def main():
    print("=" * 70)
    print("KPI Analysis - Database Cleanup")
    print("=" * 70)
    print("\n⚠️  WARNING: This will delete ALL data from the database!")
    print("   - All uploaded files")
    print("   - All analysis results")
    print("   - All user sessions")
    print("   - All logs")
    print("   - All generated reports")
    
    response = input("\n❓ Are you sure you want to continue? (yes/no): ")
    
    if response.lower() not in ['yes', 'y']:
        print("\n❌ Cleanup cancelled")
        return
    
    print("\n🚀 Starting cleanup...\n")
    
    # Clean database
    db_success = clean_database()
    
    # Clean uploaded files
    clean_uploads()
    
    # Clean reports
    clean_reports()
    
    print("\n" + "=" * 70)
    if db_success:
        print("✅ Cleanup completed successfully!")
        print("\nYou can now:")
        print("1. Start the server: python run.py")
        print("2. Login with your credentials")
        print("3. Upload fresh KPI files")
    else:
        print("⚠️  Cleanup completed with some errors")
    print("=" * 70)

if __name__ == "__main__":
    main()
