"""Application-level helpers for internetfilm-manager.

This module contains orchestration utilities that sit above individual feature
modules but below the CLI layer.  Code here may be imported by both the CLI and
by automated scripts without pulling in any interactive terminal logic.
"""

import json
import os

from integrator.config import CONFIG
from integrator.utils import get_state


def list_jobs():
    """Return a list of all job directories found under the configured work_dir.

    Each entry is a 4-tuple ``(job_id, title, path, is_curated)``.
    """
    work_dir = CONFIG.get("work_dir")
    if not work_dir or not os.path.exists(work_dir):
        return []
    jobs = []
    for f in sorted(os.listdir(work_dir)):
        path = os.path.join(work_dir, f)
        if os.path.isdir(path) and f.startswith("job_"):
            title = f
            json_path = os.path.join(path, "original.info.json")
            if os.path.exists(json_path):
                try:
                    with open(json_path, "r") as jf:
                        meta = json.load(jf)
                        title = meta.get("title", f)[:60]
                except (json.JSONDecodeError, OSError):
                    pass
            state = get_state(path)
            is_curated = state.get("is_curated", False)

            if is_curated and state.get("curated_title"):
                title = state.get("curated_title")[:60]

            jobs.append((f, title, path, is_curated))
    return jobs
