import unittest
from unittest.mock import patch

from sadb import App, MobileType, Pricing, StillRating
import sadb.appstream as appstream
from sadb.appstream_metadata import complement_flatpak_apps


def _compact_app():
    app = App(
        "example", "Example", "flathub", "app/org.example.App/x86_64/stable",
        None, None, None, None, None, None, None, None, Pricing.FREE,
        MobileType.PC_ONLY, StillRating.GOLD, None, None, None, None, None, None,
    )
    app.local_fields = {"name", "primary_src", "src_pkg_name", "pricing", "mobile", "still_rating"}
    return app


class AppStreamPipelineTests(unittest.TestCase):
    def test_real_metadata_is_loaded_before_safe_fallbacks(self):
        detail = {
            "name": "Localized Example",
            "developer_name": "Example Developer",
            "summary": "An AppStream summary",
            "description": "An AppStream description",
            "categories": ["Utility"],
        }
        app = _compact_app()

        with patch.object(appstream, "_load_flatpak_appstream_details", return_value={"org.example.App": detail}):
            appstream.enrich_apps([app])
        complement_flatpak_apps([app], pool=None)

        self.assertEqual(app.appstream_name, "Localized Example")
        self.assertEqual(app.author, "Example Developer")
        self.assertEqual(app.summary, "An AppStream summary")
        self.assertEqual(app.description, "An AppStream description")
        self.assertEqual(app.categories, ["Utility"])

    def test_unresolved_metadata_still_gets_safe_fallbacks(self):
        app = _compact_app()

        with patch.object(appstream, "_load_flatpak_appstream_details", return_value={}), \
             patch.object(appstream, "_load_components", return_value=None):
            appstream.enrich_apps([app])
        complement_flatpak_apps([app], pool=None)

        self.assertEqual(app.author, "Unknown Author")
        self.assertEqual(app.summary, "Example")
        self.assertEqual(app.description, "Example")
        self.assertEqual(app.categories, ["Unknown"])


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