from pathlib import Path
def schema_convert(base_dir: str):
    base_dir = Path(base_dir).absolute()
    schema_file = base_dir / "schema.ini"
    with open(schema_file, "r", encoding="latin-1") as frh:
        schema = frh.read()
    # schema = schema.replace('\n\n', '\n').replace('\n\n', '\n')
    tables = dict([convert_table_info(t) for t in schema[1:].split("\n[")])
    tables_with_columns = {}
    for table, details in tables.items():
        table_file = base_dir / table
        if "schema.ini" in table or not table_file.exists():
            continue
        col_names = [c.split(" ")[0] for c in details["columns"].values()]
        tables_with_columns[table] = col_names
    create_format_xml_files(base_dir, tables_with_columns)
def convert_table_info(table_info):
    info = table_info.split("]\n")
    if len(info) < 2:
        return ("", "")
    details = {}
    details["columns"] = {}
    for key, value in [row.split("=") for row in info[1].split("\n") if "=" in row]:
        if key.lower() != "colnameheader" and key.lower()[:3] == "col":
            details["columns"][key[3:]] = value
    return (info[0], details)
def create_format_xml_files(base_dir, tables_with_columns: dict[str, list[str]]):
    for table, columns in tables_with_columns.items():
        format_file = base_dir / (table + ".xml")
        record = []
        row = []
        for i, col_name in enumerate(columns, 1):
            record.append(
                f'    '
            )
            row.append(f'    ')
        record[-1] = record[-1].replace(";", "\\r\\n")
        with open(format_file, "w") as fwh:
            fwh.write(
                '\n\n  \n')
            fwh.write("\n".join(record))
            fwh.write("\n  \n  \n")
            fwh.write("\n".join(row))
            fwh.write("\n  
\n")
if __name__ == "__main__":
    schema_convert("C:\\GlobalCube_LOCOSOFT\\GCStruct_SKR51\\Kontenrahmen")