# main.py
import os
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
from config.loader import load_config, get_active_crawler_config
from database.repository import init_db
from scraper.client import get_authenticated_client
from scraper.crawler import run_collection_cycle

CONFIG = load_config()
active_crawler = get_active_crawler_config(CONFIG)

os.makedirs(os.path.dirname(os.path.abspath(CONFIG["storage"]["log_file"])), exist_ok=True)

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler(CONFIG["storage"]["log_file"], encoding="utf-8"),
        logging.StreamHandler()
    ]
)

if __name__ == "__main__":
    init_db()
    client = get_authenticated_client()

    mode_label = "DEVELOP MODE" if CONFIG.get("develop_mode", False) else "PRODUCTION MODE"
    logging.info(f"Engine launched in [{mode_label}].")

    run_collection_cycle(client)

    interval_hours = active_crawler.get("cycle_hours", 1 if CONFIG.get("develop_mode") else 3)
    scheduler = BlockingScheduler()
    scheduler.add_job(
        func=lambda: run_collection_cycle(client),
        trigger="interval",
        hours=interval_hours,
        id="hashtag_velocity_job",
        max_instances=1,
        coalesce=True
    )

    try:
        logging.info(f"Scheduler active: Recurring every {interval_hours} hour(s).")
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        logging.info("Scheduler stopped.")