#!/usr/bin/env python3
"""
Database Clear Script for Poultry Management System

This script will:
1. Delete ALL data from all tables (keeps schema intact)
2. Create a default admin user
3. Provide confirmation before making changes

Usage: python clear_database.py
"""

import os
import sys
from datetime import datetime
from werkzeug.security import generate_password_hash

# Add the current directory to Python path to import from app.py
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import app, db, User, Farm, Purchase, Sale, LedgerEntry, Account, AccountTxn, FarmLedgerEntry
from app import Employee, EmployeeAttendance, EmployeeExpense, EmployeePayment
from app import DemandOrder, OnlinePayment, Waste

def confirm_clear():
    """Ask for user confirmation before clearing the database."""
    print("=" * 60)
    print("⚠️  WARNING: DATABASE CLEAR SCRIPT ⚠️")
    print("=" * 60)
    print("This script will:")
    print("• DELETE ALL existing data from all tables")
    print("• KEEP the database schema intact")
    print("• CREATE a new admin user")
    print("=" * 60)
    
    while True:
        response = input("\nAre you sure you want to proceed? (yes/no): ").lower().strip()
        if response in ['yes', 'y']:
            return True
        elif response in ['no', 'n']:
            return False
        else:
            print("Please enter 'yes' or 'no'")

def backup_database():
    """Create a backup of the current database before clearing."""
    db_path = os.path.join('instance', 'poultry.db')
    if os.path.exists(db_path):
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_path = f"instance/poultry_backup_{timestamp}.db"
        try:
            import shutil
            shutil.copy2(db_path, backup_path)
            print(f"✅ Database backed up to: {backup_path}")
            return backup_path
        except Exception as e:
            print(f"⚠️  Warning: Could not create backup: {e}")
            return None
    return None

def clear_database():
    """Clear all data from the database while keeping schema."""
    print("\n🔄 Clearing database...")
    
    try:
        # Delete all data from tables in reverse order of dependencies
        print("• Deleting all data from tables...")
        
        # Delete dependent records first
        db.session.query(EmployeePayment).delete()
        db.session.query(EmployeeExpense).delete()
        db.session.query(EmployeeAttendance).delete()
        db.session.query(Employee).delete()
        
        db.session.query(OnlinePayment).delete()
        db.session.query(Waste).delete()
        db.session.query(AccountTxn).delete()
        db.session.query(LedgerEntry).delete()
        db.session.query(FarmLedgerEntry).delete()
        
        db.session.query(Sale).delete()
        db.session.query(Purchase).delete()
        db.session.query(DemandOrder).delete()
        
        db.session.query(Account).delete()
        db.session.query(Farm).delete()
        
        # Delete users last (after all foreign key references)
        db.session.query(User).delete()
        
        # Commit all deletions
        db.session.commit()
        
        print("✅ All data cleared successfully!")
        return True
        
    except Exception as e:
        print(f"❌ Error clearing database: {e}")
        db.session.rollback()
        return False

def create_admin_user():
    """Create the default admin user."""
    print("\n👤 Creating admin user...")
    
    try:
        # Create new admin user
        admin = User(
            email="admin@example.com",
            name="Admin",
            role="admin"
        )
        admin.set_password("admin123")
        
        db.session.add(admin)
        db.session.commit()
        
        print("✅ Admin user created successfully!")
        print("   Email: admin@example.com")
        print("   Password: admin123")
        print("   ⚠️  Please change the password after first login!")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating admin user: {e}")
        db.session.rollback()
        return False

def main():
    """Main function to orchestrate the database clear process."""
    print("🐔 Poultry Management System - Database Clear Script")
    print("=" * 60)
    
    # Check if we're in the right directory
    if not os.path.exists('app.py'):
        print("❌ Error: app.py not found. Please run this script from the project root directory.")
        sys.exit(1)
    
    # Confirm the clear operation
    if not confirm_clear():
        print("❌ Database clear cancelled by user.")
        sys.exit(0)
    
    # Create backup
    backup_path = backup_database()
    
    # Initialize Flask app context
    with app.app_context():
        # Clear database
        if not clear_database():
            print("❌ Database clear failed. Exiting.")
            sys.exit(1)
        
        # Create admin user
        if not create_admin_user():
            print("❌ Admin user creation failed. Exiting.")
            sys.exit(1)
    
    print("\n" + "=" * 60)
    print("🎉 DATABASE CLEARED SUCCESSFULLY!")
    print("=" * 60)
    print("✅ All data has been deleted")
    print("✅ Database schema is intact")
    print("✅ Admin user has been created")
    if backup_path:
        print(f"✅ Backup saved at: {backup_path}")
    print("\n📝 Next steps:")
    print("1. Start your Flask application")
    print("2. Login with admin@example.com / admin123")
    print("3. Change the admin password immediately")
    print("4. Set up your initial data (farms, accounts, customers, etc.)")
    print("=" * 60)

if __name__ == "__main__":
    main()

