"""Job CRUD layer — returns human-readable strings for LLM tool responses."""

from pathlib import Path

import structlog
from pydantic import ValidationError

from fliiq.runtime.scheduler.loader import delete_job, load_jobs, save_job
from fliiq.runtime.scheduler.models import DeliveryConfig, JobDefinition, TriggerConfig

log = structlog.get_logger()


def create_job_from_params(params: dict, project_root: Path) -> str:
    """Create a job from tool params. Returns status message for the LLM."""
    from fliiq.runtime.scheduler.daemon_utils import ensure_daemon_running

    name = params.get("name")
    prompt = params.get("prompt")

    if not name or not prompt:
        return "Error: 'name' and 'prompt' are required."

    jobs_dir = project_root / ".fliiq" / "jobs"
    jobs_dir.mkdir(parents=True, exist_ok=True)

    # Check duplicate
    if (jobs_dir / f"{name}.yaml").exists():
        return f"Error: Job '{name}' already exists. Delete it first or choose a different name."

    # Build trigger
    trigger_type = params.get("trigger_type", "cron")
    schedule = params.get("schedule")
    source = params.get("source")
    match = params.get("match")

    # Build delivery config (optional)
    delivery = None
    delivery_type = params.get("delivery_type")
    if delivery_type:
        delivery_to = params.get("delivery_to")
        if not delivery_to:
            return "Error: 'delivery_to' is required when 'delivery_type' is set."
        delivery = DeliveryConfig(type=delivery_type, to=delivery_to)

    try:
        trigger = TriggerConfig(type=trigger_type, schedule=schedule, source=source, match=match)
        job = JobDefinition(
            name=name,
            trigger=trigger,
            prompt=prompt,
            skills=params.get("skills", []),
            delivery=delivery,
        )
    except ValidationError as e:
        return f"Error creating job: {e}"

    save_job(job, jobs_dir)

    # Auto-start daemon
    try:
        daemon_ok = ensure_daemon_running(project_root)
        daemon_msg = "Daemon started." if daemon_ok else "Warning: daemon failed to start."
    except Exception as e:
        log.warning("daemon_autostart_failed", error=str(e))
        daemon_msg = f"Warning: daemon auto-start failed ({e})."

    return f"Job '{name}' created. {daemon_msg}"


def delete_job_by_name(name: str, project_root: Path) -> str:
    """Delete a job by name. Returns status message."""
    jobs_dir = project_root / ".fliiq" / "jobs"

    if not (jobs_dir / f"{name}.yaml").exists():
        return f"Error: Job '{name}' not found."

    delete_job(name, jobs_dir)
    return f"Job '{name}' deleted."


def list_jobs_summary(project_root: Path) -> str:
    """List all jobs as formatted text."""
    jobs_dir = project_root / ".fliiq" / "jobs"
    jobs = load_jobs(jobs_dir)

    if not jobs:
        return "No jobs found."

    lines = ["Jobs:"]
    for j in jobs:
        schedule = j.trigger.schedule or j.trigger.source or "-"
        status = j.state.last_status or "never run"
        enabled = "enabled" if j.enabled else "disabled"
        lines.append(f"  {j.name} | {j.trigger.type} {schedule} | {enabled} | {status} | {j.state.run_count} runs")

    return "\n".join(lines)
