# Importing the required libraries
import xml.etree.ElementTree as ET
import pandas as pd
from pathlib import Path

lang = "en"  # Language code for the output CSV
input_file = Path(__file__).parent / f'{lang}.ts'

cols = ["context", "location", "line", "source", "translation"]
rows = []

# Parsing the XML file
xmlparse = ET.parse(input_file)
root = xmlparse.getroot()
for context in root.findall('context'):
    context_name = context.find('name').text if context.find('name') is not None else ''
    for message in context.findall('message'):
        # Support multiple <location> tags per message
        locations = message.findall('location')
        if not locations:
            locations = [None]
        for location_elem in locations:
            location = location_elem.attrib.get('filename', '') if location_elem is not None else ''
            line = location_elem.attrib.get('line', '') if location_elem is not None and 'line' in location_elem.attrib else ''
            source = message.find('source').text if message.find('source') is not None else ''
            translation = message.find('translation').text if message.find('translation') is not None else ''
            rows.append({
                "context": context_name,
                "location": location,
                "line": line,
                "source": source,
                "translation": translation
            })

df = pd.DataFrame(rows, columns=cols)

# Writing dataframe to csv
df.to_csv(f'output_{lang}.csv', index=False, encoding='utf-8-sig')