import json
import os
import tempfile
import shutil
import importlib

from typing import Optional

import docker
from notebook.base.handlers import IPythonHandler, APIHandler, HTTPError
from notebook.utils import url_path_join
from pigar.core import parse_packages

from ..container.docker_service import DockerService
from .base_handler import BaseHandler


BASE_STRING = """# Autogenerated by FAIR-Cells, please adjust.
channels:
  - conda-forge
"""

def determine_packages(dir=os.getcwd()):
    libs, guess = parse_packages(dir)
    determined = [(key, libs[key].version) for key in libs.keys()]
    determined.extend([(key, None) for key in guess.keys()])

    return determined


def write_requirements(packages):
    if len(packages) == 0:
        return ""

    requirements = "dependencies:\n"
    requirements += "  - pip:\n"

    for lib, version in packages:
        if version:
            requirements += f"    - {lib}=={version}\n"
        else:
            requirements += f"    - {lib}\n"

    return requirements



class EnvironmentHandler(BaseHandler):
    def get(self, path):        
        # notebook = self.contents_manager.get(path, content=True)
        notebook_path = os.path.join(os.getcwd(), path)

        #  Create a temporary dir which will be our build context.
        with tempfile.TemporaryDirectory() as tmpdir:
            shutil.copyfile(notebook_path, tmpdir + "/notebook.ipynb")

            packages = determine_packages(tmpdir)
        
        reqs = write_requirements(packages)

        self.finish(json.dumps({
            'data': BASE_STRING + reqs
        }))
