#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import xlrd
import xlwt
import math

def check():
    if(len(sys.argv) < 2):
        print("[Error]:Not have input file")
        print("Usage : %s <filename>.xlsx"%(sys.argv[0]))
        sys.exit(1)

    if(sys.argv[1]=='-help'):
        print("Usage : %s <filename>.xlsx"%(sys.argv[0]))
        sys.exit(0)

    if(os.path.exists(sys.argv[1])==False):
        print(f"[Error]: 文件 {sys.argv[1]} 不存在")
        print("[Error]:Not such file")
        sys.exit(1)

##############################################################################
##No Copy Workbook Logic
##############################################################################
def no_copy_workbook(file_path, sheet_name):
    """
    处理Excel文件中的工作表，不复制工作表内容
    使用纯xlwt库实现
    """
    # 读取原始Excel文件
    rb = xlrd.open_workbook(file_path)
    sheet_index = rb.sheet_names().index(sheet_name)
    sheet = rb.sheet_by_index(sheet_index)

    # 获取OffsetAddress and RegName列的索引
    offset_col  = None
    regname_col = None
    bits_col    = None
    offsetWidth_col = None

    for col in range(sheet.ncols):
        if sheet.cell(0, col).value == 'OffsetAddress':
            offset_col = col
        if sheet.cell(0, col).value == 'RegName':
            regname_col = col
        if sheet.cell(0, col).value == 'Bits':
            bits_col = col
        if sheet.cell(0, col).value == 'FiledWidth':
            offsetWidth_col = col
        if offset_col is not None and regname_col is not None and bits_col is not None and offsetWidth_col is not None:
            break

    
    pattern_row = None
    if offset_col is None or regname_col is None or bits_col is None:
        print("[Error]: 未找到OffsetAddress列或RegName列或Bits列")
        return
    else:
        for row in range(sheet.nrows):
            if sheet.cell(row, offset_col).value == 'offset' or sheet.cell(row, regname_col).value == 'regname':
                pattern_row = row
                print("pattern_row is : %d"%(pattern_row))
                break

    # 创建新的Excel工作簿
    wb = xlwt.Workbook()
    ws = wb.add_sheet(sheet_name)

    bits_seq = []
    row_range = []
    bits_seq,row_range = parse_bits_sequences(file_path, sheet.name)
    is_in_sequence = False

    # The cell Not copied logic
    for col in range(sheet.ncols):
        for row in range(sheet.nrows):
            # > OffsetAddress and RegName_col col not copied
            if (pattern_row is not None and row >= pattern_row and (col == offset_col or col == regname_col)) or (sheet.cell(row, col).value == 'offset' or sheet.cell(row, col).value == 'regname'):
                continue
            # The Bits col not copied logic
            if col == bits_col:
                # 处理Bits列No copy的逻辑
                for (start, end) in row_range:
                    if row >= start and row <=end : 
                        is_in_sequence = True
                if is_in_sequence:
                    is_in_sequence = False
                    continue
            ws.write(row, col, sheet.cell(row, col).value)

    wb.save(file_path)
    print("Has copied all data to new file: %s"%(file_path))

    return offset_col, regname_col, bits_col, offsetWidth_col, pattern_row, row_range, wb, ws

##############################################################################
#########process_OffsetAddress_and_RegName_Bits_col
##############################################################################
def process_OffsetAddress_and_RegName_Bits_col(file_path, sheet_name):
    """
    处理OffsetAddress and RegName列中的"charu"内容并写回Excel(.xls)
    使用纯xlwt库实现
    """
    # 读取原始Excel文件
    #rb = xlrd.open_workbook(file_path)
    #sheet_index = rb.sheet_names().index(sheet_name)
    #sheet = rb.sheet_by_index(sheet_index)
    
    offset_col  = None
    regname_col = None
    bits_col    = None
    pattern_row = None
    row_range = []
    #No copy updated logic
    offset_col, regname_col, bits_col, offsetWidth_col, pattern_row, row_range, wb, ws = no_copy_workbook(file_path, sheet_name)

    last_valid_value = None
    first_charu_found = False
    modified = False
    
    # 处理OffsetAddress列
    for row in range(1, sheet.nrows):  # 跳过表头
        if pattern_row is None:
            print("[Note]: No need update OffsetAddress and RegName columns")
            break
        cell_value = sheet.cell(row, offset_col).value  # offset_col is the offsetAddress column
        
        if row >= pattern_row and cell_value and str(cell_value).strip():
            if not first_charu_found and last_valid_value is not None:
                first_charu_found = True
                # 将第一个"offset"替换为上一个值加4
                new_value = int(last_valid_value, 16) + 4
                ws.write(row, offset_col, f"0x{new_value:02X}")
                last_valid_value = f"0x{new_value:02X}"
                modified = True
            elif first_charu_found and last_valid_value is not None:
                # 后续"offset"继续加4
                new_value = int(last_valid_value, 16) + 4
                ws.write(row, offset_col, f"0x{new_value:02X}")
                last_valid_value = f"0x{new_value:02X}"
                modified = True
        elif cell_value and str(cell_value).strip():
            # 记录最后一个有效值
            last_valid_value = cell_value
    
    last_reg = None
    # 处理RegName列
    for row in range(1, sheet.nrows):
        if pattern_row is None:
            print("[Note]: No need update OffsetAddress and RegName columns")
            break
        cell_value = sheet.cell(row, regname_col).value
        
        if row >= pattern_row and cell_value and str(cell_value).strip():
            if last_reg:
                try:
                    num = int(last_reg.split("_")[1]) + 1
                    new_reg = f"reg_{num:02d}"
                    ws.write(row, regname_col, new_reg)
                    last_reg = new_reg
                    modified = True
                except (IndexError, ValueError):
                    print(f"Invalid Reg Name: {last_reg}")
        elif cell_value and str(cell_value).startswith('reg_'):
            last_reg = cell_value  # 记录最后一个有效的reg名称
    
    prev_right = None
    counter = 0
    # 处理Bits列
    for (start, end) in row_range:
        for row in range(start, end + 1):
            cell_value = int(sheet.cell(row, offsetWidth_col).value)
            counter += cell_value
            if row == start and cell_value and str(cell_value).strip():
                left = 32 -1
                right = left - cell_value + 1
                content = f"[{left}:{right}]" if left != right else f"[{left}]"
                ws.write(row, bits_col, content)
                modified = True
                prev_right = right
            elif row == end and cell_value and str(cell_value).strip():
                left = prev_right - 1
                right = left - cell_value + 1
                content = f"[{left}:{right}]" if left != right else f"[{left}]"
                ws.write(row, bits_col, content)
                modified = True
                prev_right = None
            else:
                if prev_right is not None:
                    left = prev_right - 1
                    right = left - cell_value + 1
                    content = f"[{left}:{right}]" if left != right else f"[{left}]"
                    ws.write(row, bits_col, content)
                    prev_right = right
                    modified = True
                else:
                    print(f"[Warning]: No previous right value for row {row} in Bits column")
        if counter != 32:
            print(f"[Warning]: Bits column total width is {counter}, expected 32 bits")
        counter = 0  # Reset counter for next sequence

        #if row >= pattern_row and cell_value and str(cell_value).strip():
        #    if cell_value == 'BitsHead':
        #        ws.write(row, bits_col, 'BitsHead')
        #        modified = True
        #    elif cell_value == 'BitsTail':
        #        ws.write(row, bits_col, 'BitsTail')
        #        modified = True
        #    elif str(cell_value).startswith('Bits'):
        #        # 处理Bits列中的其他内容
        #        ws.write(row, bits_col, f"Processed_{cell_value}")
        #        modified = True
    
    # Ensure whether the CurrentFile is modified
    if modified:
        wb.save(file_path)
        print(f"The updated file has been loaded into {file_path}")
    else:
        print("No modifications were made to the file.")
    
    return modified

###################################################################################################
##Demand: 
##1.Get the sub-sequences of BitsHead-->BitsTail of all
###################################################################################################
# ... existing code ...

def parse_bits_sequences(file_path, sheet_name):
    """
    Parse all sequences between BitsHead and BitsTail in the Bits column
    Returns a list where each element is a sublist [BitsHead, ..., BitsTail]
    """
    # Open Excel file and get the specified sheet
    rb = xlrd.open_workbook(file_path)
    sheet = rb.sheet_by_name(sheet_name)
    
    # Find the Bits column index
    bits_col = None
    for col in range(sheet.ncols):
        if sheet.cell(0, col).value == 'Bits':
            bits_col = col
            break
    
    if bits_col is None:
        print("[Error]: Bits column not found")
        return []
    
    current_sequence = []
    bits_seq = []
    start_row = None
    row_range = []
    
    in_sequence = False
    is_closed = True
    
    # Iterate through rows (skip header)
    for row in range(1, sheet.nrows):
        cell_value = str(sheet.cell(row, bits_col).value).strip()
        
        if cell_value == 'BitsHead':
            # If already in a sequence when new BitsHead found, save current sequence
            if in_sequence:
                bits_seq.append(current_sequence)
            in_sequence = True
            is_closed = False
            start_row = row
            current_sequence = [cell_value]
        elif cell_value == 'BitsTail':
            if in_sequence:
                in_sequence = False
                is_closed = True
                current_sequence.append(cell_value)
                bits_seq.append(current_sequence)
                current_sequence = []
                # sequence tuple logic
                row_range.append((start_row,row))
        elif in_sequence:
            current_sequence.append(cell_value)
    
    # Handle last unclosed sequence
    if is_closed is False:
        print("[Warning]: Last sequence not closed with BitsTail, adding to bits_seq")
        bits_seq.append(current_sequence)
    
    print("Bits sequences found:")
    for seq,(start,end) in zip(bits_seq,row_range):
        print(f"Rows {start+1}-{end+1}: {seq}")

    return bits_seq, row_range



##############################################################################
####Main()
##############################################################################
if __name__ == "__main__":
    check()
    file_path   = sys.argv[1]
    book        = xlrd.open_workbook(file_path)
    sheets_num  = len(book.sheet_names())
    print("This is OK,sheets_num is : %d" % sheets_num)


    for index in range(sheets_num):
        sheet = book.sheet_by_index(index)
        print("Sheet Name: %s"%(sheet.name))
        print("Rows: %d, Cols: %d"%(sheet.nrows, sheet.ncols))
        #for row in range(sheet.nrows):
        #    for col in range(sheet.ncols):
        #        cell_value = sheet.cell_value(row, col)
        #        if isinstance(cell_value, str):
        #            cell_value = cell_value.strip()
        #        print(f"Cell[{row}, {col}]: {cell_value}")


        # no_copy_workbook(file_path, sheet.name)
        process_OffsetAddress_and_RegName_Bits_col(file_path, sheet.name)
        print("\n")