import tempfile
import unittest
from pathlib import Path

from avmc.context import build_context
from avmc.io_ops import write_nfo
from avmc.models import MovieMetadata


class TestNfo(unittest.TestCase):
    def test_num_uses_output_number_when_subtitle(self):
        ctx = build_context(None)
        meta = MovieMetadata(
            title="title",
            number="abc-123",
            website="https://example.com",
        )
        with tempfile.TemporaryDirectory() as td:
            out = Path(td)
            nfo = write_nfo(ctx, meta, out, has_subtitle=True)
            text = nfo.read_text(encoding="utf-8")
            self.assertIn("<num>abc-123-C</num>", text)

    def test_xml_special_chars_are_escaped(self):
        ctx = build_context(None)
        meta = MovieMetadata(
            title='a&b<c>"d"',
            number="abc-123",
            studio="x&y",
            director="d<e",
            actor=['n1&n2'],
            tag=['t"g'],
            website="https://example.com/?q=a&b=1",
        )
        with tempfile.TemporaryDirectory() as td:
            out = Path(td)
            nfo = write_nfo(ctx, meta, out, has_subtitle=False)
            text = nfo.read_text(encoding="utf-8")
            self.assertIn("<title>abc-123-a&amp;bcd</title>", text)
            self.assertIn("<studio>x&amp;y</studio>", text)
            self.assertIn("<director>d&lt;e</director>", text)
            self.assertIn("<name>n1&amp;n2</name>", text)
            self.assertIn("<tag>t&quot;g</tag>", text)


if __name__ == "__main__":
    unittest.main()
