"""
Brynq Local Cron Scheduler
Allows users to schedule headless tasks to run at specific intervals.
"""

import json
import uuid
import time
from pathlib import Path
from typing import Dict, Any, List

def _schedules_file(data_dir: Path) -> Path:
    return data_dir / "schedules.json"

def _load_schedules(data_dir: Path) -> List[Dict[str, Any]]:
    path = _schedules_file(data_dir)
    if not path.exists():
        return []
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return []

def _save_schedules(data_dir: Path, schedules: List[Dict[str, Any]]) -> None:
    path = _schedules_file(data_dir)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(schedules, indent=2), encoding="utf-8")

def schedule_task(data_dir: Path, prompt: str, interval_minutes: int, model: str = None) -> str:
    """Schedule a new task."""
    schedules = _load_schedules(data_dir)
    sched_id = uuid.uuid4().hex[:8]
    schedules.append({
        "id": sched_id,
        "prompt": prompt,
        "interval_minutes": interval_minutes,
        "last_run": 0,
        "model": model,
        "created_at": time.time()
    })
    _save_schedules(data_dir, schedules)
    return sched_id

def list_schedules(data_dir: Path) -> List[Dict[str, Any]]:
    """Return all active schedules."""
    return _load_schedules(data_dir)

def run_due_schedules(data_dir: Path, execute_callback) -> List[Dict[str, Any]]:
    """Check all schedules and run the ones that are due."""
    schedules = _load_schedules(data_dir)
    now = time.time()
    executed = []
    
    updated = False
    for s in schedules:
        interval_secs = s["interval_minutes"] * 60
        if now - s.get("last_run", 0) >= interval_secs:
            # Time to run
            try:
                execute_callback(s)
            except Exception as e:
                s["last_error"] = str(e)
                
            s["last_run"] = now
            executed.append(s)
            updated = True
            
    if updated:
        _save_schedules(data_dir, schedules)
        
    return executed
