import os
import sys
import xml.etree.ElementTree as ET
import pandas as pd
from collections import OrderedDict

def extract_data(element):
    data = OrderedDict()
    for child in element:
        if len(child) > 0:
            data[child.tag] = extract_data(child)
        else:
            data[child.tag] = child.text
    return data

def flatten_ordered_dict(d, parent_key='', sep='.'):
    items = []
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, OrderedDict):
            items.extend(flatten_ordered_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return OrderedDict(items)

def process_xml_file(file_path):
    tree = ET.parse(file_path)
    root = tree.getroot()
    data = extract_data(root)
    flat_data = flatten_ordered_dict(data)

    df = pd.DataFrame([flat_data])


    df['fio_individual'] = df.apply(
        lambda row: f"{row.get('restrict_records.restrict_record.right_holders.right_holder.individual.surname', '-')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.name', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.patronymic', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.birth_date', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.birth_place', '')}",
        axis=1
    )

    df['identity_doc'] = df.apply(
        lambda row: f"{row.get('restrict_records.restrict_record.right_holders.right_holder.individual.identity_doc.document_name', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.identity_doc.document_series', '-')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.identity_doc.document_number', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.identity_doc.document_date', '')} {row.get('restrict_records.restrict_record.right_holders.right_holder.individual.identity_doc.document_issuer', '')}",
        axis=1
    )

    columns_to_keep = [
        'land_record.object.common_data.cad_number',
        'land_record.object.common_data.quarter_cad_number',
        'fio_individual',
        'identity_doc',
        'land_record.address_location.address.readable_address',
        'land_record.special_notes',
    ]

    rename_dict = {
        'land_record.object.common_data.cad_number': 'Кадастровый номер',
        'land_record.object.common_data.quarter_cad_number': 'Кадастровый номер квартала',
        'fio_individual': 'ФИО физического лица',
        'identity_doc': 'Документ, удостоверяющий личность',
        'land_record.address_location.address.readable_address': 'Адрес',
        'land_record.special_notes': 'Особые отметки',
    }

    df = df.filter(items=columns_to_keep)
    df.rename(columns=rename_dict, inplace=True)
    return df

directory_path = os.path.dirname(sys.argv[0])
all_files_data = []

for filename in os.listdir(directory_path):
    if filename.endswith('.xml'):
        file_path = os.path.join(directory_path, filename)
        df = process_xml_file(file_path)
        all_files_data.append(df)

if all_files_data:
    final_df = pd.concat(all_files_data, ignore_index=True)
    final_df.to_excel('output.xlsx', index=False)
else:
    print("No XML files found in the directory.")
 замени print на логгирование а так же добавь его в других местах что бы  я птом мог понять в чем ошибка