import unittest

from avmc.sources.javbus import JavbusScraper


class _DummyCtx:
    def __init__(self, http):
        self.http = http
        self.debug = False
        self.debug_dir = ".adc_debug"


class _RecordingHttp:
    def __init__(self):
        self.urls = []
        self._calls = 0

    def get_text(self, url, cookies=None, headers=None):
        self._calls += 1
        self.urls.append(url)
        if self._calls == 1:
            raise RuntimeError("proxy failed")
        return "<html>ok</html>"


class _FallbackHttp:
    def __init__(self):
        self.urls = []
        self._calls = 0

    def get_text(self, url, cookies=None, headers=None):
        self._calls += 1
        self.urls.append(url)
        if self._calls == 1:
            return "<html>404 not found</html>"
        return "<html>JavBus OK</html>"


class TestJavbusFetchPage(unittest.TestCase):
    def test_network_error_does_not_try_underscore_fallback(self):
        scraper = JavbusScraper()
        http = _RecordingHttp()
        ctx = _DummyCtx(http=http)

        out = scraper._fetch_page("mxgs-1417", ctx, cookies={})

        self.assertEqual(out, "")
        self.assertEqual(http.urls, ["https://www.javbus.com/mxgs-1417"])

    def test_not_found_primary_tries_underscore_fallback(self):
        scraper = JavbusScraper()
        http = _FallbackHttp()
        ctx = _DummyCtx(http=http)

        out = scraper._fetch_page("mxgs-1417", ctx, cookies={})

        self.assertEqual(out, "<html>JavBus OK</html>")
        self.assertEqual(
            http.urls,
            [
                "https://www.javbus.com/mxgs-1417",
                "https://www.javbus.com/mxgs_1417",
            ],
        )

    def test_parse_extracts_actor_from_star_name(self):
        scraper = JavbusScraper()
        html = """
        <html>
          <head><title>MXGS-1417 test title</title></head>
          <body>
            <div class="container"><h3>MXGS-1417 test title</h3></div>
            <a class="bigImage" href="https://img.example/cover.jpg"></a>
            <div class="star-name"><a href="https://www.javbus.com/star/13zh">春乃るる</a></div>
            <div class="info">
              <p><span class="header">識別碼:</span> MXGS-1417</p>
            </div>
          </body>
        </html>
        """
        data = scraper._parse(html, "mxgs-1417")
        self.assertEqual(data.actor, ["春乃るる"])


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