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

# Import logging
import logging

# Import settings from app.config
from app.config import settings

# Import SessionLocal from app.database
from app.database import SessionLocal

# Import JiraLink from app.models.jira_link
from app.models.jira_link import JiraLink

# Import jira_service from app.services
from app.services import jira_service

# Assign logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)


# Define function sync_all_jira_links
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.
    """
    # Check: not settings.JIRA_ENABLED
    if not settings.JIRA_ENABLED:
        # Return control to caller
        return

    # Assign db = SessionLocal()
    db = SessionLocal()
    # Attempt the following; catch errors below
    try:
        # Assign links = db.query(JiraLink).all()
        links = db.query(JiraLink).all()
        # Assign synced = 0
        synced = 0
        # Iterate over links
        for link in links:
            # Attempt the following; catch errors below
            try:
                # Call jira_service.sync_jira_to_aegis()
                jira_service.sync_jira_to_aegis(db, link)
                # Assign synced = 1
                synced += 1
            # Handle Exception
            except Exception as e:
                # Log warning: "Jira sync failed for link %s: %s", link.id, e
                logger.warning("Jira sync failed for link %s: %s", link.id, e)
        # Commit all pending changes to the database
        db.commit()
        # Log info: "Jira sync completed: %d/%d links updated", synced
        logger.info("Jira sync completed: %d/%d links updated", synced, len(links))
    # Handle Exception
    except Exception:
        # Log exception: "Jira sync batch job failed"
        logger.exception("Jira sync batch job failed")
    # Always execute this cleanup block
    finally:
        # Close the database session
        db.close()
