import logging
from sys import api_version

from simple_parsing import ArgumentParser
from kubernetes.client import V1PersistentVolumeClaim, V1PersistentVolumeClaimSpec, V1Pod, V1PodSpec
from kubernetes import client, config
import boto3
from mypy_boto3_s3.client import S3Client
from hurry.filesize import size
from kubernetes.client.rest import ApiException

from arc.kube.controller import Controller, ControllerOpts
from arc.data.util import S3Url


# REMOTE_SOURCE_TIMESTAMP_ANNOTATION = "creatures.io/arc/remote-source-timestamp"


# def reconcile(dataset: TabularDataSource, storage_buffer_factor: float = 0.5) -> None:
#     # refresh
#     dataset.load()

#     # check if dataset already exists locally
#     if dataset.status.synced and dataset.status.synced_source == dataset.spec.remote_source:
#         logging.info(f"dataset '{dataset.meta.name}' already synced!")
#         return

#     # get size of dataset
#     s3_url = S3Url(dataset.spec.remote_source)

#     s3_client: S3Client = boto3.client(service_name="s3", use_ssl=True)

#     response = s3_client.head_object(Bucket=s3_url.bucket(), Key=s3_url.key())
#     print("response", response)
#     file_size_bytes: int = response["ContentLength"]
#     file_size = size(file_size_bytes + (file_size_bytes * storage_buffer_factor))
#     logging.info(f"remote file size {file_size}")

#     # create PVC for dataset
#     config.load_kube_config()
#     core_v1_api = client.CoreV1Api()

#     # check if PVC exists
#     found = True
#     try:
#         pvc_found = core_v1_api.read_namespaced_persistent_volume_claim(dataset.meta.name, dataset.meta.namespace)
#     except ApiException as e:
#         if e.status == 404:
#             found = False
#         else:
#             raise e

#     # TODO: comparison of object

#     if found:
#         logging.info(f"PVC found {pvc_found}")
#         # need to check more here

#     else:
#         # create PVC
#         logging.info("no PVC found, creating...")
#         pvc = V1PersistentVolumeClaim(
#             api_version="v1",
#             kind="PersistentVolumeClaim",
#             metadata=client.V1ObjectMeta(name=dataset.meta.name, annotations={REMOTE_SOURCE_TIMESTAMP_ANNOTATION: ""}),
#             spec=V1PersistentVolumeClaimSpec(
#                 access_modes=["ReadOnlyMany"], resources={"requests": {"storage": file_size}}
#             ),
#         )
#         core_v1_api.create_namespaced_persistent_volume_claim(dataset.meta.namespace, pvc)

#     # Check if pod exists
#     found = True
#     try:
#         pod_found = core_v1_api.read_namespaced_pod(dataset.meta.name, dataset.meta.namespace)
#     except ApiException as e:
#         if e.status == 404:
#             found = False
#         else:
#             raise e

#     if found:
#         logging.info(f"pod found {pod_found}")

#     else:
#         # run a pod that mounts the container and downloads the dataset
#         pod = V1Pod(api_version="v1", kind="Pod", metadata=client.V1ObjectMeta(name=dataset.meta.name))
#         core_v1_api.create_namespaced_pod(dataset.meta.namespace)


# if __name__ == "__main__":
#     parser = ArgumentParser()
#     parser.add_arguments(ControllerOpts, dest="opts")

#     args = parser.parse_args()
#     opts: ControllerOpts = args.opts

#     ctrl = Controller[Dataset](opts)
#     ctrl.run(reconcile)
