#!/usr/bin/env python3
"""Scan LocalMods/ and generate config_player.xml with content packages."""

import os
import sys
import xml.etree.ElementTree as ET

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MODS_DIR = os.path.join(BASE, "LocalMods")
OUTPUT = os.path.join(BASE, "config_player.xml")


def find_mods():
    if not os.path.isdir(MODS_DIR):
        return []
    return sorted(
        d for d in os.listdir(MODS_DIR)
        if os.path.isfile(os.path.join(MODS_DIR, d, "filelist.xml"))
    )


def build_config(mods):
    root = ET.Element("Barotrauma")
    cp = ET.SubElement(root, "contentpackages")
    ET.SubElement(cp, "corepackage", path="Content/ContentPackages/Vanilla.xml")
    reg = ET.SubElement(cp, "regularpackages")
    for m in mods:
        ET.SubElement(reg, "package", path=f"LocalMods/{m}/filelist.xml")
    ET.indent(root)
    return ET.tostring(root, encoding="unicode", xml_declaration=True)


if __name__ == "__main__":
    mods = find_mods()
    print(f"Found {len(mods)} mod(s): {mods}")
    xml = build_config(mods)
    with open(OUTPUT, "w") as f:
        f.write(xml)
    print(f"Generated {OUTPUT}")
