
import os
import sys
import ure as re 

import calibrations
import machine


def loadModule(mod, modname=None):
    global global_scope
    if modname is None:
        modname = mod
    globals()[modname] = __import__(mod)

# These are files from firstRun and contain some calibration information
def checkAndMergeOldFiles():
    oldFileInUse = False
    try:
        print(f"System name: {calibrations.SYSTEM_NAME}")
        if calibrations.SYSTEM_NAME == "NONAME FIDO":
            print("Where are the old files? You have new, uncalibrated files here. Call initial_cal().a")
            return
    except AttributeError:
        print("Looks like we're using old files")

    oldfiles = [
        "calibrations.py",
        "configurations.py",
        "protocols.py",
        "constants.py"
    ]
    for f in oldfiles:
        if f in os.listdir():
            newname = "old_"+f
            os.rename(f, newname)
            print(f"Rename {f} {newname}")

    print("Please, copy over files:")
    print(oldfiles[:-1])
    print("After reset. Then call run2")
    machine.reset()

    return
    
def run2():
    
    import old_calibrations
    import old_configurations
    import old_protocols
    
    import calibrations
    import protocols
    import constants

        
    # merge data from old files into text of new file   
    # assumes modules have been loaded
    updateCalKey("calibrations.py", "SYSTEM_NAME", old_configurations.SYSTEM_NAME)

    updateCalKey("calibrations.py", "FORCESN", old_calibrations.FORCESN)
    updateCalKey("calibrations.py", "FORCEA", old_calibrations.FORCEA)
    updateCalKey("calibrations.py", "FORCEB", old_calibrations.FORCEB)
    updateCalKey("calibrations.py", "FORCEC", old_calibrations.FORCEC)

    machine.reset()

    return



def run():
    # check version of code running on system
    checkAndMergeOldFiles()

    # run new checkout/calibration checks

    print("MFG complete, please delete mfgFido.py and old_*.py from FIDO Flash")
    # print unit number and serial number
    # check code version


def updateCalKey(filename, key, new_value):
    """
    Updates a specific calibration variable in a Python file.
    
    Args:
        filename (str): Path to the calibration file (e.g., 'calib.py').
        key (str): The name of the variable to update (e.g., 'VALUE1').
        new_value: The new value to set. Will be converted to a string.
    """
    try:
        # 1. Read all lines from the file
        with open(filename, 'r') as f:
            lines = f.readlines()

        new_lines = []
        found = False
        
        # Define the regex pattern:
        # ^ starts the line
        # {key} matches the variable name
        # \s*=\s* matches the equals sign with optional whitespace
        # .* matches the old value and anything else on the line (like comments)
        pattern = r'^{}\s*=\s*.*'.format(key)

        # 2. Iterate through lines and apply the substitution
        for line in lines:
            if re.match(pattern, line):
                # Found the line. Construct the replacement line.
                # Use a raw string for the value to handle types correctly (e.g., "hello" vs 123.45)
                
                # Check if the old value was likely a string literal (e.g., in quotes)
                # If so, keep the quotes for the new value (assuming new_value is a simple string)
                if '"' in line or "'" in line:
                    new_line_content = f"{key} = '{new_value}'"
                else:
                    new_line_content = f"{key} = {new_value}"

                # Preserve trailing comments/whitespace from the original line if they exist
                # Find the start of the description/comment, if any.
                comment_match = re.search(r'(\s*#.*)', line)
                if comment_match:
                    comment = comment_match.group(1)
                    new_line = new_line_content + comment + '\n'
                else:
                    new_line = new_line_content + '\n'

                new_lines.append(new_line)
                found = True
            else:
                new_lines.append(line)

        if not found:
            print(f"Warning: Key '{key}' not found in {filename}. File not modified.")
            return

        # 3. Write all lines back to the file (overwriting the original)
        with open(filename, 'w') as f:
            for line in new_lines:
                f.write(line)
            f.flush()

        print(f"Successfully updated '{key}' in {filename} to '{new_value}'.")

    except Exception as e:
        print(f"An error occurred: {e}")

def mergeData():
    # assumes modules have been loaded
    updateCalKey("calibrations.py", "SYSTEM_NAME", old_configurations.SYSTEM_NAME)

    updateCalKey("calibrations.py", "FORCESN", old_calibrations.FORCESN)
    updateCalKey("calibrations.py", "FORCEA", old_calibrations.FORCEA)
    updateCalKey("calibrations.py", "FORCEB", old_calibrations.FORCEB)
    updateCalKey("calibrations.py", "FORCEC", old_calibrations.FORCEC)

    updateCalKey("calibrations.py", "VOLUME_UNITS", old_calibrations.VOLUME_UNITS)

    return