#!/usr/bin/env python3
"""
Add the awesome-jellyfin local plugin repository to Jellyfin's system.xml.
Creates a timestamped backup of system.xml first.

This script auto-detects the Synq Core Jellyfin container config path first,
then falls back to the standard /var/lib/jellyfin/config path.
"""

import os
import shutil
import sys
from datetime import datetime
from pathlib import Path
from xml.etree import ElementTree as ET

SYNQ_SYSTEM_XML = Path("/opt/synq-deploy/synq-tv-kids/jellyfin/config/config/system.xml")
STANDARD_SYSTEM_XML = Path("/var/lib/jellyfin/config/system.xml")
REPO_NAME = os.environ.get("REPO_NAME", "Awesome Jellyfin (local)")
REPO_URL = os.environ.get(
    "REPO_URL", "https://plugins.teamspeed.team/jellyfin-plugin-repo.json"
)


def find_system_xml() -> Path:
    if SYNQ_SYSTEM_XML.exists():
        return SYNQ_SYSTEM_XML
    if STANDARD_SYSTEM_XML.exists():
        return STANDARD_SYSTEM_XML
    raise FileNotFoundError(
        f"Jellyfin system.xml not found at {SYNQ_SYSTEM_XML} or {STANDARD_SYSTEM_XML}"
    )


def main() -> int:
    try:
        system_xml = find_system_xml()
    except FileNotFoundError as exc:
        print(exc)
        return 1

    backup = system_xml.with_suffix(
        f".xml.bak.{datetime.now().strftime('%Y%m%d%H%M%S')}"
    )
    shutil.copy2(system_xml, backup)
    print(f"Backed up system.xml to {backup}")

    tree = ET.parse(system_xml)
    root = tree.getroot()

    repos = root.find("PluginRepositories")
    if repos is None:
        repos = ET.SubElement(root, "PluginRepositories")

    # Check if our repo is already present.
    for repo in repos.findall("RepositoryInfo"):
        url_el = repo.find("Url")
        if url_el is not None and url_el.text == REPO_URL:
            print(f"Repository '{REPO_URL}' already present in Jellyfin config.")
            return 0

    repo = ET.SubElement(repos, "RepositoryInfo")
    name = ET.SubElement(repo, "Name")
    name.text = REPO_NAME
    url = ET.SubElement(repo, "Url")
    url.text = REPO_URL
    enabled = ET.SubElement(repo, "Enabled")
    enabled.text = "true"

    tree.write(system_xml, encoding="utf-8", xml_declaration=True)
    print(f"Added repository '{REPO_NAME}' -> {REPO_URL}")
    print("Restart Jellyfin for the change to take effect:")
    print("  docker restart synq-jellyfin")
    return 0


if __name__ == "__main__":
    sys.exit(main())
