#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sqlite3
from datetime import datetime
import sys
import importlib.util

# Add the parent directory to path so we can import the app
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)

# Import models directly to avoid circular import
from models import db, User, Category

def rebuild_database(app_instance=None):
    """Completely rebuilds the database by dropping and recreating all tables."""
    if app_instance is None:
        # Only import app if it's not provided as a parameter
        from app import app as app_instance
        from app import db_path
    else:
        # Get db_path from app_instance config
        db_path = app_instance.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
    
    with app_instance.app_context():
        print(f"Database path: {db_path}")
        
        # Back up existing database if it exists
        if os.path.exists(db_path):
            backup_path = db_path + '.backup'
            try:
                import shutil
                shutil.copy2(db_path, backup_path)
                print(f"Backed up existing database to {backup_path}")
            except Exception as e:
                print(f"Warning: Could not create backup - {str(e)}")
        
        # Ensure directory exists
        os.makedirs(os.path.dirname(db_path), exist_ok=True)
        
        # Drop all tables and recreate them
        print("Dropping all tables...")
        db.drop_all()
        
        print("Creating all tables...")
        db.create_all()
        
        # Create admin user
        print("Creating admin user...")
        admin = User(
            username='admin',
            email='admin@example.com',
            is_admin=True,
            created_at=datetime.utcnow()
        )
        admin.set_password('admin')
        db.session.add(admin)
        
        # Create regular user
        print("Creating regular user...")
        user = User(
            username='user',
            email='user@example.com',
            is_admin=False,
            created_at=datetime.utcnow()
        )
        user.set_password('user')
        db.session.add(user)
        
        try:
            # Commit to generate user IDs
            db.session.commit()
            print("Users created successfully!")
            
            # Create default categories
            print("Creating default categories...")
            # Instead of directly importing create_default_categories, call it through app_instance
            create_default_categories_func = getattr(sys.modules['app'], 'create_default_categories')
            create_default_categories_func()
            
            print("Database rebuild completed successfully!")
            return True
        except Exception as e:
            db.session.rollback()
            print(f"Error during database rebuild: {str(e)}")
            raise

if __name__ == "__main__":
    rebuild_database() 