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

This script will:
1. Drop all existing database tables
2. Recreate all tables with fresh schema
3. Create a default admin user
4. Provide confirmation before making changes

Usage: python reset_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

def confirm_reset():
    """Ask for user confirmation before resetting the database."""
    print("=" * 60)
    print("⚠️  WARNING: DATABASE RESET SCRIPT ⚠️")
    print("=" * 60)
    print("This script will:")
    print("• DELETE ALL existing data in the database")
    print("• DROP all tables")
    print("• RECREATE all tables with fresh schema")
    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 reset."""
    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 reset_database():
    """Reset the database by dropping and recreating all tables."""
    print("\n🔄 Resetting database...")
    
    try:
        # Drop all tables
        print("• Dropping all existing tables...")
        db.drop_all()
        
        # Create all tables
        print("• Creating fresh database schema...")
        db.create_all()
        
        print("✅ Database schema recreated successfully!")
        return True
        
    except Exception as e:
        print(f"❌ Error resetting database: {e}")
        return False

def create_admin_user():
    """Create the default admin user."""
    print("\n👤 Creating admin user...")
    
    try:
        # Check if admin already exists
        existing_admin = User.query.filter_by(role="admin").first()
        if existing_admin:
            print("• Admin user already exists, skipping creation")
            return True
        
        # 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 reset process."""
    print("🐔 Poultry Management System - Database Reset 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 reset operation
    if not confirm_reset():
        print("❌ Database reset cancelled by user.")
        sys.exit(0)
    
    # Create backup
    backup_path = backup_database()
    
    # Initialize Flask app context
    with app.app_context():
        # Reset database
        if not reset_database():
            print("❌ Database reset 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 RESET COMPLETED SUCCESSFULLY!")
    print("=" * 60)
    print("✅ All tables have been recreated")
    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, etc.)")
    print("=" * 60)

if __name__ == "__main__":
    main()
