"""TBX (TermBase eXchange) format handler."""

from __future__ import annotations

from lxml import etree

from ..model import TranslationCatalog, TranslationEntry, EntryState
from ..registry import register_format
from .base import BaseFormat


@register_format("tbx")
class TbxFormat(BaseFormat):
    def read(self, filepath: str) -> TranslationCatalog:
        tree = etree.parse(filepath)
        root = tree.getroot()
        catalog = TranslationCatalog()

        # Handle both TBX v2 (martif) and v3 (tbx)
        for entry_el in root.iter("termEntry", "conceptEntry"):
            lang_sets = entry_el.findall("langSet")
            source = ""
            target = ""
            for ls in lang_sets:
                lang = ls.get("{http://www.w3.org/XML/1998/namespace}lang", "") or ls.get("lang", "")
                tig = ls.find(".//tig") or ls.find(".//ntig")
                if tig is not None:
                    term = tig.find("term")
                else:
                    term = ls.find(".//term")
                text = term.text if term is not None and term.text else ""
                if not source:
                    source = text
                    if not catalog.source_language:
                        catalog.source_language = lang
                else:
                    target = text
                    if not catalog.target_language:
                        catalog.target_language = lang

            eid = entry_el.get("id", source)
            state = EntryState.TRANSLATED if target else EntryState.UNTRANSLATED
            catalog.entries.append(TranslationEntry(
                key=eid, source=source, target=target, state=state,
            ))

        return catalog

    def write(self, catalog: TranslationCatalog, filepath: str) -> None:
        root = etree.Element("martif", type="TBX")
        header = etree.SubElement(root, "martifHeader")
        fi = etree.SubElement(header, "fileDesc")
        src = etree.SubElement(fi, "sourceDesc")
        p = etree.SubElement(src, "p")
        p.text = "Generated by l10n-conv"

        body = etree.SubElement(root, "text")
        body_el = etree.SubElement(body, "body")

        for i, entry in enumerate(catalog.entries):
            te = etree.SubElement(body_el, "termEntry", id=entry.key or str(i + 1))

            ls1 = etree.SubElement(te, "langSet")
            ls1.set("{http://www.w3.org/XML/1998/namespace}lang", catalog.source_language or "en")
            tig1 = etree.SubElement(ls1, "tig")
            t1 = etree.SubElement(tig1, "term")
            t1.text = entry.source or entry.key

            if entry.target:
                ls2 = etree.SubElement(te, "langSet")
                ls2.set("{http://www.w3.org/XML/1998/namespace}lang", catalog.target_language or "und")
                tig2 = etree.SubElement(ls2, "tig")
                t2 = etree.SubElement(tig2, "term")
                t2.text = entry.target

        tree = etree.ElementTree(root)
        tree.write(filepath, xml_declaration=True, encoding="utf-8", pretty_print=True)
