import os
import sys
import time
import logging

# Ensure src is in the python path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")))

from app.core.logging import setup_logging
from app.db.session import get_session_factory
from app.models.hermes_config import HermesTaskConfig
from app.services.hermes_scheduler import hermes_scheduler

logger = logging.getLogger("hermes_daemon")

def init_default_config():
    """Ensure there is at least one active global_risk_scan task in the database."""
    session_factory = get_session_factory()
    db = session_factory()
    try:
        # 初始化 global_risk_scan
        existing_risk = db.query(HermesTaskConfig).filter_by(task_type="global_risk_scan").first()
        if not existing_risk:
            logger.info("No global_risk_scan config found. Initializing default config.")
            db.add(HermesTaskConfig(
                task_type="global_risk_scan",
                cron_expression="0 2 * * *", 
                is_enabled=True
            ))
            
        # 初始化 weekly_expense_report
        existing_report = db.query(HermesTaskConfig).filter_by(task_type="weekly_expense_report").first()
        if not existing_report:
            logger.info("No weekly_expense_report config found. Initializing default config.")
            db.add(HermesTaskConfig(
                task_type="weekly_expense_report",
                cron_expression="0 9 * * 1", # 每周一早9点（在简化版中暂时代表周报频率）
                is_enabled=True
            ))

        # 初始化 employee_behavior_profile_scan：默认关闭，避免全员画像过频。
        existing_profile = db.query(HermesTaskConfig).filter_by(task_type="employee_behavior_profile_scan").first()
        if not existing_profile:
            logger.info("No employee_behavior_profile_scan config found. Initializing default config.")
            db.add(HermesTaskConfig(
                task_type="employee_behavior_profile_scan",
                cron_expression="0 8 * * 1",
                is_enabled=False
            ))
             
        db.commit()
    except Exception as e:
        logger.error(f"Failed to initialize default config: {e}")
    finally:
        db.close()


def main():
    setup_logging()
    logger.info("Initializing Hermes Background Daemon...")
    
    # 注入默认配置
    init_default_config()
    
    # 启动调度器
    hermes_scheduler.start()
    
    logger.info("Hermes Daemon is running. Press Ctrl+C to stop.")
    try:
        while True:
            time.sleep(1) # 主线程保持存活
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt received. Shutting down...")
        hermes_scheduler.shutdown()
        logger.info("Shutdown complete.")

if __name__ == "__main__":
    main()
