"""Kubernetes CronJob discovery."""

from typing import List, Dict, Any

try:
    from kubernetes import client, config
    K8S_AVAILABLE = True
except ImportError:
    K8S_AVAILABLE = False


def discover_k8s_jobs() -> List[Dict[str, Any]]:
    """Discover Kubernetes CronJobs."""
    if not K8S_AVAILABLE:
        return []

    jobs = []

    try:
        # Try in-cluster config first, then kubeconfig
        try:
            config.load_incluster_config()
        except:
            config.load_kube_config()

        batch_v1 = client.BatchV1Api()
        core_v1 = client.CoreV1Api()

        # List all namespaces
        namespaces = core_v1.list_namespace()
        for ns in namespaces.items:
            namespace = ns.metadata.name

            # List CronJobs in namespace
            cronjobs = batch_v1.list_namespaced_cron_job(namespace)

            for cj in cronjobs.items:
                schedule = cj.spec.schedule
                job_name = cj.metadata.name

                # Extract container command
                containers = cj.spec.job_template.spec.template.spec.containers
                if containers:
                    container = containers[0]
                    command = " ".join(container.command or [])
                    if container.args:
                        command += " " + " ".join(container.args)
                else:
                    command = "unknown"

                # Generate external ID
                import hashlib
                fingerprint_input = f"{schedule}|{command}|{namespace}|{job_name}"
                external_id = hashlib.sha256(fingerprint_input.encode()).hexdigest()
                command_hash = hashlib.sha256(command.encode()).hexdigest()[:12]

                jobs.append({
                    "externalId": external_id,
                    "name": job_name,
                    "schedule": schedule,
                    "source": "kubernetes",
                    "commandHash": command_hash,
                    "location": f"{namespace}/{job_name}",
                    "enabled": cj.spec.suspend is not True,
                    "command": command,
                    "namespace": namespace,
                })

    except Exception as e:
        # Silently fail if not in K8s or no permissions
        pass

    return jobs

