# src/celery_app.py
"""
Celery 앱 초기화
"""
import os
import logging
from celery import Celery
from dotenv import load_dotenv

# 로깅 설정
logger = logging.getLogger(__name__)

# 환경 변수 로드 (main.py와 동일한 로직)
# .env 파일에서 ENVIRONMENT만 읽고, 해당 환경 파일(.env.development or .env.production) 로드
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
main_env_file = os.path.join(project_root, '.env')

if os.path.exists(main_env_file):
    # .env 파일에서 ENVIRONMENT만 읽기
    load_dotenv(main_env_file, override=False)
    environment = os.getenv('ENVIRONMENT', 'development').lower()
    
    # ENVIRONMENT 값에 따라 실제 환경 파일 선택
    if environment == 'production':
        env_file = os.path.join(project_root, '.env.production')
    else:
        env_file = os.path.join(project_root, '.env.development')
    
    # 선택된 환경 파일 로드
    if os.path.exists(env_file):
        load_dotenv(env_file, override=True)
        logger.info(f"Celery 환경: {environment}, 환경 변수 파일 로드: {env_file}")
    else:
        logger.warning(f"환경 변수 파일을 찾을 수 없음: {env_file}")
else:
    logger.warning(f"메인 환경 변수 파일을 찾을 수 없음: {main_env_file}, 기본 .env 파일 로드 시도")
    load_dotenv()

# Redis URL 설정 (환경 변수 또는 기본값)
REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379/0')

# Celery 앱 생성 (Flask 앱 없이도 작동)
celery = Celery(
    'mlink_subscription',
    backend=REDIS_URL,
    broker=REDIS_URL
)

celery.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone='Asia/Seoul',
    enable_utc=True,
    task_track_started=True,
    task_time_limit=30 * 60,  # 30분
    task_soft_time_limit=25 * 60,  # 25분
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=1000,
    broker_connection_retry_on_startup=True,  # 시작 시 브로커 연결 재시도
    beat_schedule={
        # 매시간 정기구독 갱신 체크
        'check-subscription-renewals': {
            'task': 'src.tasks.check_subscription_renewals',
            'schedule': 3600.0,  # 1시간마다 체크
        },
        # 매일 자정에 만료된 구독 정리
        'cleanup-expired-subscriptions': {
            'task': 'src.tasks.cleanup_expired_subscriptions',
            'schedule': 86400.0,  # 24시간마다
        },
    }
)

# 태스크 모듈 import (태스크 등록을 위해 필수)
# 이 import는 태스크를 등록하기 위해 필요합니다
try:
    import src.tasks  # noqa: F401
except ImportError:
    pass  # tasks 모듈이 없어도 계속 진행

# Flask 앱이 있을 때만 컨텍스트 태스크 설정
def init_celery_with_app(app):
    """Flask 앱으로 Celery 초기화 (컨텍스트 태스크 설정)"""
    class ContextTask(celery.Task):
        """Flask 애플리케이션 컨텍스트를 포함하는 Celery 태스크"""
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)
    
    celery.Task = ContextTask
    return celery

