"rough sketch"

from speedbuild.utils.parsers.python.parser import PythonBlockParser, indentCode


extra="""
from django.shortcuts import render
from django.utils import timezone
from rest_framework import status
from rest_framework.response import Response
from .models import RevenueLog
from .models import Prefrence
"""

code ="""
    if paymentStatus == True and amount >= log.amount_in_rand:
        now = timezone.now()
        date = now.date()
        month = now.date().strftime("%B")
        year = now.date().year

        log.paid = True
        log.date = date
        log.month = month
        log.year = year
        log.jannis_percentage = jannis_percentage
        log.save()

        # set consultation to paid
        consultation = log.item
        consultation.has_paid = True
        consultation.amount_paid = amount
        consultation.date_paid = timezone.now()
        consultation.save()

        # TODO : jannis revenue log here

        jannis_revenue = RevenueLog()
        jannis_revenue.for_jannis = True
        jannis_revenue.date = date
        jannis_revenue.month = month
        jannis_revenue.year = year
        jannis_revenue.revenue_for = log.revenue_for
        jannis_revenue.amount_in_rand = log.amount_in_rand
        jannis_revenue.paid = True
        jannis_revenue.item = log.item
        jannis_revenue.paid_by = log.paid_by
        jannis_revenue.jannis_percentage = jannis_percentage
        jannis_revenue.save()

        # TODO : send confirmation email
        # TODO : send zoom meeting link 
    else:
        print("Emmanuel is Good")
        num=100
"""


def getCodeChildren(code,alltheWay=False):

    """Get nested code blocks from indented code.
    This function splits a code string into chunks based on indentation levels. It can either
    preserve the original indentation or strip all whitespace from the beginning of lines.
    Args:
        code (str): The input code string to be split into chunks
        alltheWay (bool, optional): If True, strips all leading whitespace from lines.
            If False, only removes one level of indentation. Defaults to False.
    Returns:
        list: A list of code chunks, where each chunk is a string containing one or more lines
            that were at the same indentation level in the original code.
    Example:
        >>> code = '''def foo():
        ...     x = 1
        ...     if True:
        ...         y = 2
        ... '''
        >>> getCodeChildren(code)
        ['x = 1\nif True:\n    y = 2']
    """

    block = []
    chunks = []
    has_subchunk = False
    lines = code.split("\n")

    for line in lines:

        if len(line.strip()) == 0:
            block.append("\n")
            continue

        if alltheWay:
            line = line.strip()
            block.append(line)
            continue

        if line.startswith(" "):
            if not has_subchunk:
                _,line = line.split("    ",1)
                # print(line)
        else:
            has_subchunk = True
            if len(block) > 0:
                chunks.append("\n".join(block))
                block = [] 
    
        block.append(line)
    
    if len(block) > 0:
        chunks.append("\n".join(block))

    # print(len(chunks),chunks)
    return chunks

def getChildres(code):

    data_structure_open_characters = ["{","[","("]
    data_structure_close_characters = ["}","]",")"]

    code = code.strip()
    checks = ["def","class"]

    chunks = []
    skip_parsing = False

    if code.split(" ",1)[0].strip() in checks:
        segments = code.split("\n")

        if len(segments) > 1:
            chunks.append(segments[0])
            code = "\n".join(segments[1:])

            chunks = getCodeChildren(code)
 
            chunks = PythonBlockParser().parse_code("\n".join(chunks))

            if len(chunks) > 0:
                skip_parsing = True
                for i in range(0,len(chunks)):
                    chunks[i] = indentCode(chunks[i])

                chunks.insert(0,segments[0])

    elif code[-1] in data_structure_close_characters: # is a list | set | dictionary | tuple | function or class call
        opening_char = data_structure_open_characters[data_structure_close_characters.index(code[-1])]
        opening, code = code.split(opening_char,1)
        code = code[:-1]
        chunks.append(opening)
        code = getCodeChildren(code,True)
    else:
        print("here")
        code = "\n".join(getCodeChildren(code))
        chunks = getCodeChildren(code)
        skip_parsing = True

    if not skip_parsing:
        chunks = PythonBlockParser().parse_code(code)
    
    for chunk in chunks:
        print(chunk)
        print("\n","-"*30,"\n")


getChildres(code)
# print(code)