import cv2
import matplotlib.pyplot as plt

def line_alg(path):
    def process(ImagePath):
        originalmage = cv2.imread(ImagePath)
        originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
        shape = originalmage.shape[:2]
        print(shape)
        if originalmage is None:
            print("Can not find any image. Choose appropriate file")
            sys.exit()
        ReSized1 = originalmage
        grayScaleImage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2GRAY)
        ReSized2 = grayScaleImage
        smoothGrayScale = cv2.medianBlur(grayScaleImage, 5)
        ReSized3 = smoothGrayScale
        getEdge = cv2.adaptiveThreshold(smoothGrayScale, 255,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY, 9, 9)
        ReSized4 = cv2.medianBlur(getEdge,3)

        return ReSized4, grayScaleImage, ReSized3
        
    edge, gray, blur = process(path)
    edge_bit = (edge > 255/2) * 1.0
    plt.imshow(edge_bit, cmap = 'gray')

    w, h = edge_bit.shape
    edge_bit_new = cv2.resize(edge_bit, (round(h/6),round(w/6)))
    w, h = edge_bit_new.shape

    edge_bit_new = (edge_bit_new>0.5)*1.0

    thin_edge = edge_bit_new.copy()
    for i in range(w):
        for j in range(h-1):
            if thin_edge[i,j]==0 and thin_edge[i,j+1]==0:
                thin_edge[i,j]=1

    plt.imshow(thin_edge, cmap='gray')

    def is_valid_move(matrix, x, y, visited):
        rows, cols = len(matrix), len(matrix[0])
        return 0 <= x < rows and 0 <= y < cols and matrix[x][y] == 1 and not visited[x][y]

    def dfs(matrix, x, y, visited, path):
        visited[x][y] = True
        path.append([x, y])

        # Define possible moves (up, down, left, right)
        moves = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]

        for move in moves:
            new_x, new_y = x + move[0], y + move[1]
            if is_valid_move(matrix, new_x, new_y, visited):
                dfs(matrix, new_x, new_y, visited, path)

    def find_paths(matrix):
        rows, cols = len(matrix), len(matrix[0])
        visited = [[False for _ in range(cols)] for _ in range(rows)]
        paths = []

        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == 1 and not visited[i][j]:
                    path = []
                    dfs(matrix, i, j, visited, path)
                    if path:
                        paths.append(path)

        return paths

    result = find_paths(1-thin_edge)
    # print(result)

    flattened_list = []
    for sublist in result:
        flattened_list.append([sublist[0][0],sublist[0][1],0])
        flattened_list.append([sublist[0][0],sublist[0][1],1])
        if len(sublist) > 0:
            for i, element in enumerate(sublist[:-1]):
                flattened_list.append([sublist[i][0],sublist[i][1],1])
    return thin_edge, flattened_list
