# backend/run.py - PRODUCTION READY VERSION

import os
import ssl
import logging
from flask import jsonify
from app import app, db, socketio
from models.company import Company
from models.user import User
from models.calendar_event import CalendarEvent
from models.time_log import TimeLog
from models.client import Client
from models.project import Project
from models.calendar_source import CalendarSource
from models.calendar import Calendar
from models.sync_job import SyncJob
## from services.report_scheduler import report_scheduler
from datetime import datetime
from tasks.master_data_scheduler import master_data_scheduler

logger = logging.getLogger(__name__)




def initialize_database():
    """Initialize database with sample data (safe - checks existence first)"""
    with app.app_context():
        try:
            # Check if companies exist, create if they don't
            companies_data = [
                {'name': 'Agentic AI Consulting', 'domain': 'agentic.com'},
                {'name': 'Tech Solutions Inc', 'domain': 'techsolutions.com'},
                {'name': 'Alpha Corporation', 'domain': 'alphacorp.com'},
            ]
            
            for company_data in companies_data:
                company = Company.query.filter_by(domain=company_data['domain']).first()
                if not company:
                    company = Company(**company_data)
                    db.session.add(company)
                    print(f"[OK] Created company: {company_data['name']}")
            
            db.session.commit()
            
            from utils.db_session_manager import DBSessionManager
            companies = DBSessionManager.get_companies(include_inactive=True)
            print(f"\n Database verification: {len(companies)} companies found")
            
            for company in companies:
                print(f"   - {company['name']} (ID: {company['id']}, active: {company['is_active']})")
            
            # Create admin user if it doesn't exist
            agentic_company = Company.query.filter_by(domain='agentic.com').first()
            if agentic_company:
                admin = User.query.filter_by(username='admin').first() or User.query.filter_by(email='admin@agentic.com').first()
                if not admin:
                    admin = User(
                        username='admin',
                        email='admin@agentic.com',
                        first_name='Admin',
                        last_name='User',
                        role='admin',
                        company_id=agentic_company.id,
                        status='active'
                    )
                    admin.set_password('admin123')
                    db.session.add(admin)
                    db.session.commit()
                    print("[OK] Created admin user")
            
            print("\n Available login credentials:")
            admin_user = User.query.filter_by(email='admin@agentic.com').first()
            if admin_user:
                print(f"   Admin: {admin_user.email} / admin123")
            
        except Exception as e:
            print(f"[WARNING] Error during initialization: {str(e)}")
            import traceback
            traceback.print_exc()
            db.session.rollback()

def setup_routes():
    """Setup all routes"""
    # Group your imports by category
    # Auth & Users
    from routes.auth_routes import auth_bp
    from routes.user_routes import users_bp
    from routes.rbac_routes import rbac_bp
    from routes.twofa_routes import twofa_bp
    from routes.settings_routes import settings_bp
    from routes.alert_preferences_routes import alert_prefs_bp
    
    # Core Features
    ## from routes.calendar_source_routes import calendar_source_bp
    ## from routes.time_log_routes import time_log_bp
    ## from routes.calendar_routes import calendar_bp
    ## from routes.project_routes import projects_bp
    ## from routes.client_routes import clients_bp
    from routes.dashboard_preferences_routes import dashboard_prefs_bp
    from routes.activity_routes import activity_bp
    
    # Business Features
    ## from routes.budget_routes import budget_bp
    ## from routes.team_routes import team_bp
    ## from routes.service_routes import service_bp
    ## from routes.tasks_routes import tasks_bp
    
    # Service Platform
    from routes.platform_role_routes import platform_role_bp
    ## from routes.service_platform_routes import service_platform_bp
    ## from routes.hr_workflow_routes import hr_workflow_bp
    ## from routes.payment_routes import payment_bp
    ## from routes.booking_calendar_routes import booking_calendar_bp
    ## from routes.workflow_routes import workflow_bp
    ## from routes.document_routes import document_bp
   
    # HR
    ## from routes.recruitment_routes import recruitment_bp
    ## from routes.athena_workflow_routes import athena_workflow_bp

    # Procurement
    ## from routes.procurement_routes import procurement_bp
 
    # Admin & System
    from routes.admin_routes import admin_bp
    ## from routes.master_data_routes import master_data_bp
    from routes.module_routes import module_bp  # ADD THIS
    from routes.status_routes import status_bp
    from routes.tenant_routes import tenant_bp
    from routes.company_permission_routes import company_perm_bp
    from routes.admin_log_routes import admin_log_bp
    from routes.admin_notification_routes import admin_notification_bp
    from routes.admin_archive_routes import admin_archive_bp
    from routes.admin_monitoring_routes import admin_monitoring_bp
    from routes.admin_session_routes import admin_session_bp
    from routes.permission_routes import permission_bp
    
    # Analytics & Reports
    ## from routes.analytics_routes import analytics_bp
    ## from routes.report_routes import report_bp
    from routes.service_analytics_routes import service_analytics_bp
    ## from routes.time_log_analytics_routes import time_log_analytics_bp
    
    # Utilities
    ## from routes.export_routes import export_bp
    from routes.search_routes import search_bp
    from routes.notifications_routes import notifications_bp
    ## from routes.ai_insights_routes import ai_insights_bp
    ## from routes.chart_data_routes import chart_bp
    from routes.dashboard_routes import dashboard_bp
    from routes.debug_routes import debug_bp

    ## from routes.ai_time_log_routes import ai_time_log_bp
    #from routes.ai_routes import ai_bp
    from routes.ai_status_routes import ai_status_bp
    from routes.company_routes import companies_bp
    from routes.portal_routes import portal_bp
    from routes.calendar_events_routes import calendar_events_bp
    from routes.approval_routes import approval_bp
    from routes.company_settings_routes import company_settings_bp

    # AI Agents
    #from routes.ai_agent_routes import ai_agent_bp
    ## from routes.agentic_routes import agentic_bp

    # Grassroots
    from routes.grassroots_event_routes import grassroots_bp

    
    # Register blueprints
    # Auth & Users
    app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')         # Blueprint has /api/v1/auth
    app.register_blueprint(users_bp, url_prefix='/api/v1/users')       # Blueprint has /api/v1/users
    app.register_blueprint(rbac_bp, url_prefix='/api/v1/rbac')         # Blueprint has /api/v1/rbac
    app.register_blueprint(twofa_bp)
    app.register_blueprint(settings_bp)
    app.register_blueprint(alert_prefs_bp)
    ## app.register_blueprint(tasks_bp)

    # ADD THIS LINE - Register calendar_source_bp
    ## app.register_blueprint(calendar_source_bp, url_prefix='/api/v1/calendar-sources')
    
    # Core Features
    ## app.register_blueprint(time_log_bp, url_prefix='/api/v1/time-logs')   # /api/v1/time-logs
    ## app.register_blueprint(calendar_bp, url_prefix='/api/v1/calendar')    # /api/v1/calendar
    ## app.register_blueprint(projects_bp, url_prefix='/api/v1/projects')    # /api/v1/projects
    ## app.register_blueprint(clients_bp, url_prefix='/api/v1/clients')      # /api/v1/clients
    app.register_blueprint(dashboard_prefs_bp)
    app.register_blueprint(activity_bp)
    
    # Business Features
    ## app.register_blueprint(budget_bp, url_prefix='/api/v1/budget')        # /api/v1/budget
    ## app.register_blueprint(team_bp, url_prefix='/api/v1/team')            # /api/v1/team
    ## app.register_blueprint(service_bp, url_prefix='/api/v1/services')     # /api/v1/services
    
    # Service Platform
    app.register_blueprint(platform_role_bp)
    ## app.register_blueprint(service_platform_bp, url_prefix='/api/v1/service-platform')   # /api/v1/service-platform
    ## app.register_blueprint(hr_workflow_bp, url_prefix='/api/v1/hr')                      # /api/v1/hr
    ## app.register_blueprint(payment_bp, url_prefix='/api/v1/payments')                    # /api/v1/payments
    ## app.register_blueprint(booking_calendar_bp, url_prefix='/api/v1/bookings/calendar')  # /api/v1/bookings/calendar
    ## app.register_blueprint(document_bp)

    # HR
    ## app.register_blueprint(recruitment_bp)
    ## app.register_blueprint(athena_workflow_bp)

    # Procurement
    ## app.register_blueprint(procurement_bp)
    
    # Admin & System
    app.register_blueprint(admin_bp, url_prefix='/api/v1/admin')              # /api/v1/admin
    ## app.register_blueprint(master_data_bp, url_prefix='/api/v1/master-data')  # /api/v1/master-data
    app.register_blueprint(module_bp, url_prefix='/api/v1/modules')           # /api/v1/modules  
    app.register_blueprint(status_bp, url_prefix='/api/v1/status')            # /api/v1/status
    app.register_blueprint(tenant_bp, url_prefix='/api/v1/tenant')            # /api/v1/tenant
    app.register_blueprint(company_perm_bp)
    app.register_blueprint(admin_log_bp)
    app.register_blueprint(admin_notification_bp)
    app.register_blueprint(admin_archive_bp)
    app.register_blueprint(admin_monitoring_bp)
    app.register_blueprint(admin_session_bp)
    ## app.register_blueprint(workflow_bp)
    app.register_blueprint(permission_bp)
    
    # Analytics & Reports
    ## app.register_blueprint(analytics_bp, url_prefix='/api/v1/analytics')                   # /api/v1/analytics
    ## app.register_blueprint(report_bp, url_prefix='/api/v1/reports')                        # /api/v1/reports
    app.register_blueprint(service_analytics_bp, url_prefix='/api/v1/service-analytics')   # /api/v1/service-analytics
    ## app.register_blueprint(time_log_analytics_bp)
    
    # Utilities
    ## app.register_blueprint(export_bp, url_prefix='/api/v1/export')                   # /api/v1/export
    app.register_blueprint(search_bp, url_prefix='/api/v1/search')                   # /api/v1/search
    app.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')     # /api/v1/notifications
    ## app.register_blueprint(chart_bp, url_prefix='/api/v1/charts')                    # /api/v1/charts
    app.register_blueprint(dashboard_bp, url_prefix='/api/v1/dashboard')             # /api/v1/dashboard
    app.register_blueprint(debug_bp, url_prefix='/api/v1/debug')                     # /api/v1/debug
    
    app.register_blueprint(companies_bp, url_prefix='/api/v1/companies')
    ## app.register_blueprint(ai_time_log_bp, url_prefix='/api/v1/ai/time-logs')
    #app.register_blueprint(ai_bp, url_prefix='/api/v1/ai')
    app.register_blueprint(ai_status_bp, url_prefix='/api/v1/ai/status') 
    ## app.register_blueprint(ai_insights_bp, url_prefix='/api/v1/ai/insights')
    app.register_blueprint(portal_bp, url_prefix='/api/v1/portal')
    app.register_blueprint(calendar_events_bp, url_prefix='/api/v1/calendar-events')
    app.register_blueprint(approval_bp)
    app.register_blueprint(company_settings_bp)

    # AI Agents
    #app.register_blueprint(ai_agent_bp, url_prefix='/api/v1/ai-agent')
    ## app.register_blueprint(agentic_bp)

    # Grassroots
    app.register_blueprint(grassroots_bp)

   
    print(f"[OK] {len(app.blueprints)} blueprints registered")
    for blueprint in app.blueprints:
        print(f"   - {blueprint}: {app.blueprints[blueprint].url_prefix}")
    
    # ADD THIS TEMPORARILY FOR DEBUGGING
    with app.app_context():
        print("\n[LIST] Module routes:")
        for rule in app.url_map.iter_rules():
            if 'modules' in str(rule):
                print(f"  {rule.methods} - {rule}")
    
    print("[OK] Routes registered")
 
 
    # Health check (keep at root)
    @app.route('/api/health')
    def api_health_check():
        """Health check endpoint for SSL certificate acceptance"""
        return jsonify({
            'status': 'healthy',
            'message': 'API is running',
            'timestamp': datetime.now().isoformat()
        }), 200

    print(f"[OK] {len(app.blueprints)} blueprints registered")
    for blueprint in app.blueprints:
        print(f"   - {blueprint}: {app.blueprints[blueprint].url_prefix}")

    # Basic routes
    @app.route('/')
    def index():
        return {'message': 'Agentic AI Time Logger API', 'status': 'running'}
    
    @app.route('/api/test-db')
    def test_db():
        from sqlalchemy import text
        result = db.session.execute(text('SELECT 1')).fetchone()
        return {'message': 'Database connection successful', 'result': str(result)}
    
    print("[OK] Routes registered")


    @app.route('/debug/routes', methods=['GET'])
    def debug_routes():
        """List all registered routes"""
        routes = []
        for rule in app.url_map.iter_rules():
            routes.append({
                'endpoint': rule.endpoint,
                'methods': list(rule.methods),
                'path': str(rule)
            })
        return jsonify({
            'total_routes': len(routes),
            'routes': routes
        })

    
def start_ai_services():
    """Start AI services if enabled"""
    ai_enabled = os.getenv('AI_ENABLED', 'false').lower() == 'true'
    scheduler_enabled = os.getenv('SCHEDULER_ENABLED', 'false').lower() == 'true'
    
    # Check schedule availability inside the function
    schedule_available = False
    try:
        import schedule
        schedule_available = True
    except ImportError:
        pass
    
    if ai_enabled:
        try:
            from services.ai_service import ai_service
            print(f"[OK] AI service initialized (available: {ai_service.is_available()})")
            
            if scheduler_enabled:
                try:
                    from services.agentic_scheduler import agentic_scheduler
                    from services.reminder_scheduler import reminder_scheduler
                    
                    # Initialize scheduler with app
                    agentic_scheduler.init_app(app)
                    reminder_scheduler.init_app(app)
                    
                    # Start scheduler
                    agentic_success = agentic_scheduler.start()
                    reminder_success = reminder_scheduler.start()
                    
                    if agentic_success:
                        print(" Agentic AI scheduler started")
                        print("   Scheduled tasks:")
                        print("   - 08:00 - Morning preview")
                        print("   - 12:00 - Midday check")  
                        print("   - 17:00 - Evening review")
                        print("   - 20:00 - Next day preparation")
                        print("   - Hourly - Productivity checks (9am-6pm)")
                        
                        if schedule_available:
                            # Add team sync monitor (daily at 23:00)
                            schedule.every().day.at("23:00").do(agentic_scheduler._team_sync_monitor)
                            
                            # Add auto-delegation check (hourly)
                            schedule.every().hour.do(agentic_scheduler._auto_delegation_check)
                            
                            # Add company auto-log (daily at 01:00)
                            schedule.every().day.at("01:00").do(agentic_scheduler._company_auto_log)
                            
                            print("   Platform features: team sync, auto-delegation, auto-log")
                        else:
                            print("   [WARNING] 'schedule' module not installed - advanced scheduling disabled")
                    else:
                        print("[WARNING] Agentic scheduler failed to start")
                    
                    if reminder_success:
                        print(" Reminder scheduler started")
                        print("   - Smart reminders based on user preferences")
                        print("   - Daily/weekly threshold alerts")
                        print("   - Manager notifications for low utilization")
                        
                except ImportError as e:
                    print(f"[WARNING] Could not import scheduler: {e}")
                    print("   To enable scheduler: pip install schedule")
                except Exception as e:
                    print(f"[WARNING] Failed to start agentic scheduler: {e}")
            else:
                print(" Agentic scheduler disabled (set SCHEDULER_ENABLED=true in .env to enable)")
            
        except ImportError as e:
            print(f"[WARNING] Could not import AI services: {e}")
    else:
        print(" AI features disabled (set AI_ENABLED=true in .env to enable)")


def start_background_services():
    """Start all background services"""
    # Start AI services (existing)
    ## start_ai_services()
    
    # Start report scheduler
    ##try:
    ##    report_scheduler.start(app)
    ##    print("[OK] Report scheduler started")
    ##except Exception as e:
    ##    print(f"[WARNING]  Failed to start report scheduler: {e}")

    # Start master data scheduler
    try:
        master_data_scheduler.init_app(app)  # Initialize with app
        master_data_scheduler.start()
        print("[OK] Master data scheduler started")
    except Exception as e:
        print(f"[WARNING]  Failed to start master data scheduler: {e}")
    
    # Approval task scheduler
    ## try:
    ##    from apscheduler.schedulers.background import BackgroundScheduler
    ##    from tasks.approval_escalation import run_escalation_check
    ##    from tasks.approval_reminders import send_approval_reminders
        
    ##    approval_scheduler = BackgroundScheduler()
    ##    approval_scheduler.add_job(func=run_escalation_check, trigger="interval", minutes=5)
    ##    approval_scheduler.add_job(func=send_approval_reminders, trigger="interval", hours=1)
    ##    approval_scheduler.start()
    ##    print("[OK] Approval escalation & reminder scheduler started")
    ## except Exception as e:
    ##    print(f"[WARNING] Failed to start approval scheduler: {e}")
    
    # Error report scheduler
    ## try:
    ##    from apscheduler.schedulers.background import BackgroundScheduler
    ##    from tasks.error_report_tasks import send_company_error_summary, send_weekly_error_summary
        
    ##    error_report_scheduler = BackgroundScheduler()
        
    ##    # Daily at 8:00 AM
    ##    error_report_scheduler.add_job(
    ##        func=send_company_error_summary,  # Changed from send_daily_error_summary
    ##        args=[None],  # Will need to handle None case
    ##        trigger="cron", 
    ##        hour=8, 
    ##        minute=0,
    ##        id="daily_error_summary"
    ##    )
        
    ##    # Weekly on Monday at 9:00 AM
    ##    error_report_scheduler.add_job(
    ##        func=send_weekly_error_summary, 
    ##        trigger="cron", 
    ##        day_of_week="mon", 
    ##        hour=9, 
    ##        minute=0,
    ##        id="weekly_error_summary"
    ##    )
        
    ##    error_report_scheduler.start()
    ##    print("[OK] Error report scheduler started (daily 8am, weekly Monday 9am)")
        
    ## except Exception as e:
    ##    print(f"[WARNING] Failed to start error report scheduler: {e}")

    # System health monitor (every 15 minutes)
    ## try:
    ##    from tasks.system_health_monitor import check_system_health
    ##    health_scheduler = BackgroundScheduler()
    ##    health_scheduler.add_job(
    ##        func=check_system_health,
    ##        trigger="interval",
    ##        minutes=15,
    ##        id="system_health_check"
    ##    )
    ##    health_scheduler.start()
    ##    print("[OK] System health monitor started (every 15 minutes)")
    ## except Exception as e:
    ##    print(f"[WARNING] Failed to start health monitor: {e}")


    # Audit archival (daily at 2 AM)
    try:
        from apscheduler.schedulers.background import BackgroundScheduler
        from tasks.audit_archival_tasks import run_daily_archival, run_monthly_archive_cleanup
        
        archival_scheduler = BackgroundScheduler()
        archival_scheduler.add_job(
            func=run_daily_archival,
            trigger="cron",
            hour=2,
            minute=0,
            id="daily_audit_archival"
        )
        archival_scheduler.add_job(
            func=run_monthly_archive_cleanup,
            trigger="cron",
            day=1,
            hour=3,
            minute=0,
            id="monthly_archive_cleanup"
        )
        archival_scheduler.start()
        print("[OK] Audit archival scheduler started (daily at 2am, monthly cleanup on 1st at 3am)")
    except Exception as e:
        print(f"[WARNING] Failed to start archival scheduler: {e}")

    
    # Database connection pool monitoring (every 5 minutes)
    try:
        from apscheduler.schedulers.background import BackgroundScheduler
        from tasks.database_monitor import check_db_connections
        
        db_monitor = BackgroundScheduler()
        db_monitor.add_job(
            func=check_db_connections,
            trigger="interval",
            minutes=5,
            id="db_connection_monitor"
        )
        db_monitor.start()
        print("[OK] Database connection monitor started (every 5 minutes)")
    except Exception as e:
        print(f"[WARNING] Failed to start DB monitor: {e}")



if __name__ == '__main__':
    # Determine if running in production
    is_production = os.getenv('FLASK_ENV') == 'production'
    
    print("[ROCKET] Starting Agentic AI Time Logger API...")
    print(f"   Environment: {'PRODUCTION' if is_production else 'DEVELOPMENT'}")
    
    # Initialize database FIRST
    initialize_database()
    
    # Setup routes SECOND
    setup_routes()

    # Start background services THIRD
    start_background_services()

    # Get port and host from environment
    port = int(os.getenv('PORT', 5059))
    host = os.getenv('HOST', '0.0.0.0')
    
    # Set debug mode based on environment
    debug_mode = not is_production
    
    # Check if we should use HTTPS (development only)
    use_https = os.getenv('USE_HTTPS', 'false').lower() == 'true' and not is_production

    if use_https and not is_production:
        print(f" Secure server will run on: https://localhost:{port}")
        print(f" WebSocket URL: wss://localhost:{port}/socket.io/")
        
        cert_file = os.getenv('SSL_CERT_FILE', os.path.join(os.path.dirname(__file__), 'localhost+2.pem'))
        key_file = os.getenv('SSL_KEY_FILE', os.path.join(os.path.dirname(__file__), 'localhost+2-key.pem'))
        
        # Verify files exist
        if not os.path.exists(cert_file) or not os.path.exists(key_file):
            print(f"[ERROR] Certificate files not found!")
            print(f"   Looking for: {cert_file}")
            print(f"   Falling back to HTTP...")
            socketio.run(app, debug=debug_mode, host=host, port=port)
        else:
            print(f"[OK] Found certificate files")
            
            # Create SSL context
            ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_context.load_cert_chain(cert_file, key_file)
            socketio.run(app, debug=debug_mode, host=host, port=port, ssl_context=ssl_context)
    else:
        if is_production:
            print(f" Production server running on: http://{host}:{port}")
            print(f"   Note: SSL is handled by cPanel/Apache, not by Flask")
        else:
            print(f" Development server running on: http://{host}:{port}")
        socketio.run(app, debug=debug_mode, host=host, port=port)


# For cPanel WSGI compatibility (when using run.py as entry point)
application = app

