import unittest

from sadb import App, MobileType, Pricing, StillRating
from appstream_metadata import complement_flatpak_apps


class _Array:
    def __init__(self, values):
        self.values = values

    def as_array(self):
        return self.values


class _Developer:
    def get_name(self):
        return "Example Developer"


class _Provided:
    def get_items(self):
        return ["text/plain"]


class _Component:
    def get_name(self): return "Example"
    def get_developer(self): return _Developer()
    def get_summary(self): return "An AppStream summary"
    def get_description(self): return "An AppStream description"
    def get_categories(self): return ["Utility"]
    def get_keywords(self): return ["example"]
    def get_provided_for_kind(self, _kind): return _Provided()
    def get_project_license(self): return "MIT"
    def get_url(self, kind): return "https://example.test/" if "HOMEPAGE" in str(kind) else None


class _Pool:
    def __init__(self, component=None):
        self.component = component

    def get_components_by_bundle_id(self, _kind, _package, _match_prefix):
        return _Array([self.component] if self.component else [])

    def get_components_by_id(self, _app_id):
        return _Array([])


def _app(summary=None):
    return App(
        "example", "Example", "flathub", "app/org.example.App/x86_64/stable",
        "https://flathub.test/icon.png", None, summary, None, None, None, None,
        None, Pricing.FREE, MobileType.PC_ONLY, StillRating.GOLD, None, None,
        None, ["https://flathub.test/screenshot.png"], None, None,
    )


class AppStreamMetadataTests(unittest.TestCase):
    def test_complements_compact_record_without_replacing_repo_media(self):
        app = _app()
        complement_flatpak_apps([app], pool=_Pool(_Component()))

        self.assertEqual(app.summary, "An AppStream summary")
        self.assertEqual(app.description, "An AppStream description")
        self.assertEqual(app.author, "Example Developer")
        self.assertEqual(app.categories, ["Utility"])
        self.assertEqual(app.icon_url, "https://flathub.test/icon.png")
        self.assertEqual(app.screenshot_urls, ["https://flathub.test/screenshot.png"])

    def test_curated_summary_wins(self):
        app = _app("Curated summary")
        complement_flatpak_apps([app], pool=_Pool(_Component()))
        self.assertEqual(app.summary, "Curated summary")

    def test_missing_component_gets_stillcenter_safe_fallbacks(self):
        app = _app()
        complement_flatpak_apps([app], pool=_Pool())
        self.assertEqual(app.summary, "Example")
        self.assertEqual(app.description, "Example")
        self.assertEqual(app.author, "Unknown Author")
        self.assertEqual(app.categories, ["Unknown"])


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