#!/usr/bin/env python3
"""
Local development runner for Savly Platform
This script handles database initialization and starts the Flask app
"""

import os
import sys
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Add current directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import app, db
from models import *  # Import all models

def init_database():
    """Initialize database tables"""
    with app.app_context():
        try:
            # Create all tables
            db.create_all()
            print("✅ Database tables created successfully")
            
            # Check if we have any data
            from models import Currency, Member
            
            # Create default currency if none exists
            if not Currency.query.first():
                default_currency = Currency(
                    name='Bangladeshi Taka',
                    code='BDT',
                    symbol='৳',
                    is_default=True
                )
                db.session.add(default_currency)
                db.session.commit()
                print("✅ Default currency (BDT) created")
            
            print("🎯 Database initialization completed")
            
        except Exception as e:
            print(f"❌ Database initialization failed: {e}")
            return False
    
    return True

def main():
    """Main function to run the application"""
    print("🏗️  Initializing Savly Platform for local development...")
    
    # Initialize database
    if not init_database():
        print("❌ Failed to initialize database. Exiting.")
        sys.exit(1)
    
    # Get configuration
    host = os.environ.get('HOST', '0.0.0.0')
    port = int(os.environ.get('PORT', 5001))
    debug = os.environ.get('FLASK_DEBUG', 'True').lower() == 'true'
    
    print(f"\n🚀 Starting Savly Platform...")
    print(f"🌐 URL: http://{host}:{port}")
    print(f"📊 Debug mode: {debug}")
    print(f"🗄️  Database: {os.environ.get('DATABASE_URL', 'Not configured')}")
    print(f"\n🔑 Default Login Credentials:")
    print(f"   Superadmin: admin / admin123")
    print(f"   Group Admin: amader / 22558822")
    print(f"   Members: M001-M022 / 1234")
    print(f"\n🎯 Application starting on port {port}...")
    print("─" * 50)
    
    try:
        app.run(
            host=host,
            port=port,
            debug=debug,
            use_reloader=debug
        )
    except KeyboardInterrupt:
        print("\n👋 Application stopped by user")
    except Exception as e:
        print(f"\n❌ Application error: {e}")

if __name__ == '__main__':
    main()