#!/usr/bin/env python3

import sys
import xml.etree.ElementTree as ET

def time_to_seconds(t):
    # HH:MM:SS.mmm → float seconds
    h, m, s = t.split(":")
    return int(h) * 3600 + int(m) * 60 + float(s)

def get_text(el, path):
    n = el.find(path)
    return n.text.strip() if n is not None and n.text else ""

def main(xml_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()

    for edition in root.findall("EditionEntry"):
        edition_uid = get_text(edition, "EditionUID") or "unknown"

        chapters = []

        for atom in edition.findall("ChapterAtom"):
            row = {
                "start": time_to_seconds(get_text(atom, "ChapterTimeStart")),
                "enabled": get_text(atom, "ChapterFlagEnabled"),
                "hidden": get_text(atom, "ChapterFlagHidden"),
            }

            # collect multilingual displays
            for disp in atom.findall("ChapterDisplay"):
                lang = get_text(disp, "ChapterLanguage")
                text = get_text(disp, "ChapterString")

                if lang:
                    row[f"display.{lang}"] = text

            chapters.append(row)

        # deterministic order
        chapters.sort(key=lambda x: x["start"])

        r'''
        # collect all columns (stable order)
        cols = ["start", "enabled", "hidden"]
        extra_cols = sorted(
            c for r in chapters for c in r.keys()
            if c not in cols
        )
        cols.extend(extra_cols)
        '''

        # collect all columns (deduplicated)
        col_set = {"start", "enabled", "hidden"}

        for r in chapters:
            col_set.update(r.keys())

        col_set -= {"start", "enabled", "hidden"}

        extra_cols = sorted(col_set)
        cols = ["start", "enabled", "hidden"] + extra_cols
        cols.sort()

        out_file = f"chapters.ed{edition_uid}.tsv"

        with open(out_file, "w", encoding="utf-8") as f:
            f.write("\t".join(cols) + "\n")

            for r in chapters:
                f.write("\t".join(str(r.get(c, "")) for c in cols) + "\n")

        print(f"Wrote {out_file}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: chapters_to_tsv.py chapters.xml")
        sys.exit(1)

    main(sys.argv[1])