import os
import subprocess
import kopf
import time
import re
from configClient import generateClientYaml
from configEndpoint import patchNseYaml, generateEndpointYaml
from utility import execute_command, generateNetworkService, generateTemplate, generateNamespace, getLastSetup
from kubernetes import client, config

#def get_running_pods_in_namespace(namespace):
#    config.load_kube_config()
#    v1 = client.CoreV1Api()
#
#    running_pods = []
#    pods = v1.list_namespaced_pod(namespace)
#
#    for pod in pods.items:
#        if pod.status.phase == 'Running' and not re.search(r'nsc|nse', pod.metadata.name):
#            running_pods.append(pod.metadata.name)
#    return running_pods
#
#def pod_is_running(pod):
#    print(pod.status.phase)
#    return pod.status.phase == 'Running'
#
#def watch_running_pods():
#    config.load_kube_config()
#    v1 = client.CoreV1Api()
#    namespace = 'nsm-chain'
#
#    while True:
#        pods = v1.list_namespaced_pod(namespace)
#        for pod in pods.items:
#            if pod_is_running(pod):
#                handle_running_pod(pod)
#        time.sleep(10)
#
#def handle_running_pod(pod):
#    print(f"Pod {pod.metadata.name} in namespace {pod.metadata.namespace} è in stato Running.")
#.
#
@kopf.on.create('kopf.dev/v1', 'SecurityChain')
def configureChain(body, namespace, **kwargs):
    generateNamespace()
    generateNetworkService()
    generateTemplate()
    generateEndpointYaml()
    generateClientYaml()
    

@kopf.on.update('kopf.dev/v1', 'SecurityChain')  
def updateChain(body, old, new, diff, namespace, **kwargs):
    print("SecurityChain object updated.")

@kopf.on.delete('kopf.dev/v1', 'securitychains')
def delete_namespace_fn(spec, **kwargs):
    namespace = spec.get('namespace')
    if not namespace:
        return
    api = client.CoreV1Api()

    try:
        api.delete_namespace(name=namespace, body=client.V1DeleteOptions())
        print(f'Deleted namespace: {namespace}')
    except client.ApiException as e:
        print(f'Failed to delete namespace: {e}')





if __name__ == '__main__':

    #This part is needed to retrieve the obj and the crd files.
    script_directory = os.path.dirname(os.path.abspath(__file__))
    api_directory = os.path.join(script_directory, "API")
    latest_setup = getLastSetup(api_directory)
    crd_yaml_path = os.path.join(api_directory, latest_setup, "crd.yaml")
    obj_yaml_path = os.path.join(api_directory, latest_setup, "obj.yaml")
 

    #Configuration for NSM
    spire_command = "kubectl apply -k https://github.com/networkservicemesh/deployments-k8s/examples/spire/single_cluster?ref=e420c8c572eee763dfb1af42e3703eb48d337760"
    spire_wait1 = "kubectl wait -n spire --timeout=2m --for=condition=ready pod -l app=spire-server"
    spire_wait2 = "kubectl wait -n spire --timeout=2m --for=condition=ready pod -l app=spire-agent"
    spire_command_2 = "kubectl apply -f https://raw.githubusercontent.com/networkservicemesh/deployments-k8s/e420c8c572eee763dfb1af42e3703eb48d337760/examples/spire/single_cluster/clusterspiffeid-template.yaml"
    config_command = "kubectl apply -k https://github.com/networkservicemesh/deployments-k8s/examples/basic?ref=e420c8c572eee763dfb1af42e3703eb48d337760"

    #Configuration for CRD and Operator
    crd_command = f"kubectl apply -f {crd_yaml_path}"
    obj_command = f"kubectl apply -f {obj_yaml_path}"
    execute_command(spire_command)
    execute_command(spire_wait1)
    execute_command(spire_wait2)
    execute_command(spire_command_2)
    execute_command(config_command)
    execute_command(crd_command)
subprocess.run(['kopf','run','script.py'])
