#!/usr/bin/env python3
"""
Parsing di hermes cron list output (testuale, non JSON).
Usare in script no_agent che devono leggere i cron job.
"""
import subprocess, os, re

def get_cron_jobs():
    """Legge i cron job da hermes CLI (output testuale)."""
    env = os.environ.copy()
    env['PATH'] = f"{os.path.expanduser('~/.local/bin')}:{env.get('PATH', '')}"
    try:
        result = subprocess.check_output(
            'hermes cron list 2>/dev/null',
            shell=True, text=True, timeout=15, env=env
        )
    except:
        return []

    jobs = []
    current = None
    for line in result.splitlines():
        line_s = line.rstrip()  # IMPORTANT: use rstrip(), NOT strip() — strip removes leading spaces needed by regex
        
        # Match job_id + stato: "  a066d6c0271e [active]"  (2 spazi iniziali)
        m = re.match(r'\s{2}([a-f0-9]+)\s+\[(\w+)\]', line_s)
        if m:
            current = {"job_id": m.group(1), "enabled": m.group(2) == 'active'}
            jobs.append(current)
            continue
        if current is None:
            continue
        
        # Match campi indentati: "    Name:      dashboard-refresh" (4 spazi iniziali)
        m2 = re.match(r'\s{4}(\w[\w\s-]*?):\s+(.*)', line_s)
        if m2:
            key = m2.group(1).strip().lower().replace(' ', '_')
            val = m2.group(2).strip()
            if key == 'name':
                current['name'] = val
            elif key == 'schedule':
                current['schedule'] = val
            elif key == 'last_run':
                # "2026-06-14T13:56:30.673079+02:00  ok"
                parts = val.rsplit(None, 1)
                current['last_run_at'] = parts[0] if len(parts) > 1 else val
                current['last_status'] = parts[-1] if len(parts) > 1 else None

    return jobs
