print("initializing python...")
import re

from pyscript import window


class App:
    def __init__(self):
        self.initialized = False

    async def initialize(self, files_store, editor_store):
        self.files_store = files_store
        self.editor_store = editor_store
        self.initialized = True
        print("LAB INITIALIZED")

    def copy_to_editor(self, content):
        print(f"Copying {content}")
        self.editor_store.insertAtCursor("dummy.py", f"\n{content}")

    def get_code(self, file_type, message_text):
        """Given a message text, returns any python code in the following format
        '''<file_type>
        {code here}
        '''
        """
        code_prefix = f"```{file_type}"
        if code_prefix in message_text:
            chunks = message_text.split(code_prefix)
            print(message_text)
            print(chunks)
            return chunks[1].split("```")[0]

    async def parse_agent_response(self, message):
        files = {"python": {}, "toml": {}, "html": {}}

        text_resp = message.content[0].text

        for file_type in files:
            code = ""
            pattern = re.compile(rf"```{file_type}(.*?)```", re.DOTALL)
            matches = pattern.findall(text_resp)
            print("file_type", file_type)
            print("matches", matches)
            if matches:
                match = matches[0]
                print("Match!", match)
                print(f"Extracted code: {match.strip()}")
                code += f"\n{match.strip()}"

                if file_type == "python":
                    file_name = "main.py"
                elif file_type == "html":
                    file_name = "index.html"
                else:
                    file_name = "pyscript.toml"

                window.console.log(self.editor_store)
                if not self.editor_store.editors.has(file_name):
                    await self.files_store.openTab(file_name)

                print(f"Saving {file_name}")
                await self.editor_store.setFileContent(file_name, f"\n{code}")

                await self.files_store.saveFile(file_name)

        self.iframe_preview_ref.value.refreshIframe()


# Expose the Python "Lab" App to the JS side
window.lab = App()

print("python engine initialized.")
