"""Scheduled job — syncs all Jira links hourly."""

import logging

from app.config import settings
from app.database import SessionLocal
from app.models.jira_link import JiraLink
from app.services import jira_service

logger = logging.getLogger(__name__)


def sync_all_jira_links() -> None:
    """Pull latest status from Jira for every stored link.

    Silently skips if ``JIRA_ENABLED`` is ``False``.  Individual link
    failures are logged but do not abort the rest of the batch.
    """
    if not settings.JIRA_ENABLED:
        return

    db = SessionLocal()
    try:
        links = db.query(JiraLink).all()
        synced = 0
        for link in links:
            try:
                jira_service.sync_jira_to_aegis(db, link)
                synced += 1
            except Exception as e:
                logger.warning("Jira sync failed for link %s: %s", link.id, e)
        db.commit()
        logger.info("Jira sync completed: %d/%d links updated", synced, len(links))
    except Exception:
        logger.exception("Jira sync batch job failed")
    finally:
        db.close()
