"""Linux cron job discovery."""

import hashlib
import subprocess
from pathlib import Path
from typing import List, Dict, Any


def _parse_cron_line(line: str, source: str) -> Dict[str, Any]:
    """Parse a single cron line into a job dict."""
    line = line.strip()

    # Skip comments and empty lines
    if not line or line.startswith("#"):
        return None

    # Split into schedule and command
    parts = line.split(None, 5)
    if len(parts) < 6:
        return None

    # Check if it's a user-specific cron (user field present)
    # Format: minute hour day month weekday user command
    # Or standard: minute hour day month weekday command
    if len(parts) == 6:
        schedule = " ".join(parts[:5])
        command = parts[5]
        user = None
    elif len(parts) == 7:
        # /etc/crontab format with user
        schedule = " ".join(parts[:5])
        user = parts[5]
        command = parts[6]
    else:
        return None

    # Generate fingerprint
    fingerprint_input = f"{schedule}|{command}|{source}"
    external_id = hashlib.sha256(fingerprint_input.encode()).hexdigest()

    # Generate command hash (for deduplication)
    command_hash = hashlib.sha256(command.encode()).hexdigest()[:12]

    # Generate job name from command
    name = command.split()[0] if command else "unknown"
    if "/" in name:
        name = Path(name).name

    return {
        "externalId": external_id,
        "name": name,
        "schedule": schedule,
        "source": "cron",
        "commandHash": command_hash,
        "location": source,
        "enabled": True,
        "command": command,
        "user": user,
    }


def discover_cron_jobs() -> List[Dict[str, Any]]:
    """Discover all cron jobs on the system."""
    jobs = []

    # Discover user crontab
    try:
        result = subprocess.run(
            ["crontab", "-l"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            for line in result.stdout.splitlines():
                job = _parse_cron_line(line, "crontab")
                if job:
                    jobs.append(job)
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass

    # Discover system crontab
    system_crontab = Path("/etc/crontab")
    if system_crontab.exists():
        try:
            with open(system_crontab, "r") as f:
                for line in f:
                    job = _parse_cron_line(line, str(system_crontab))
                    if job:
                        jobs.append(job)
        except Exception:
            pass

    # Discover cron.d directory
    cron_d = Path("/etc/cron.d")
    if cron_d.exists() and cron_d.is_dir():
        for cron_file in cron_d.iterdir():
            if cron_file.is_file() and not cron_file.name.startswith("."):
                try:
                    with open(cron_file, "r") as f:
                        for line in f:
                            job = _parse_cron_line(line, str(cron_file))
                            if job:
                                jobs.append(job)
                except Exception:
                    pass

    return jobs

