from aisi.__system__.imports import *


class Help:
    ####################################################################################// Main
    def extractBlocks(text=""):
        if text.strip() == "":
            return {}

        rand = secrets.token_urlsafe(21)
        text += f"\n({rand})"
        lines = text.splitlines()
        files = {}
        i = 0
        n = len(lines)

        while i < n:
            line = lines[i].strip()
            if lines[i].startswith("[") and line.endswith("]"):
                filename = line[1:-1].strip()
                i += 1

                while i < n and not lines[i].lstrip().startswith("```"):
                    i += 1

                if i < n and lines[i].lstrip().startswith("```"):
                    i += 1
                content_start = i
                j = i

                while j < n:
                    l = lines[j].strip()
                    if lines[j].startswith("[") and l.endswith("]"):
                        break
                    j += 1

                content_lines = lines[content_start:j]
                while content_lines and content_lines[-1].strip().startswith("```"):
                    content_lines.pop()

                content = "\n".join(content_lines).strip()
                parts = content.split("```")
                result = "```".join(parts[:-1]).strip() if len(parts) > 1 else content
                files[filename] = result.replace(f"({rand})", "")
                i = j
            else:
                i += 1

        return files

    ####################################################################################// Helpers
