import os
import unittest


class TestLegalLinksLangResolution(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        # 让 Settings 能顺利构造（避免因必填 env 缺失导致导入时报错）
        os.environ.setdefault("DATABASE_URL", "mysql+aiomysql://u:p@127.0.0.1:3306/mindfulness_dev?charset=utf8mb4")
        os.environ.setdefault("REDIS_URL", "redis://:p@127.0.0.1:6379/0")
        os.environ.setdefault("CELERY_BROKER_URL", "redis://:p@127.0.0.1:6379/0")

    def setUp(self) -> None:
        # 每个用例都清理 settings 缓存，避免环境变量修改不生效
        from app.core.config import get_settings

        get_settings.cache_clear()

    def test_resolve_lang_default_en(self) -> None:
        from app.api.v1.legal import _resolve_lang

        self.assertEqual(_resolve_lang(None), "en")
        self.assertEqual(_resolve_lang(""), "en")

    def test_resolve_lang_tc_for_zh(self) -> None:
        from app.api.v1.legal import _resolve_lang

        self.assertEqual(_resolve_lang("zh"), "tc")
        self.assertEqual(_resolve_lang("zh-Hant"), "tc")
        self.assertEqual(_resolve_lang("zh-TW"), "tc")
        self.assertEqual(_resolve_lang("zh-HK"), "tc")
        self.assertEqual(_resolve_lang("tc"), "tc")

    def test_pick_urls_fallback_to_en(self) -> None:
        # 不配置 tc 链接时，应回退到 en
        os.environ["LEGAL_PRIVACY_URL_EN"] = "https://example.com/en-privacy"
        os.environ["LEGAL_TERMS_URL_EN"] = "https://example.com/en-terms"
        os.environ.pop("LEGAL_PRIVACY_URL_TC", None)
        os.environ.pop("LEGAL_TERMS_URL_TC", None)

        from app.core.config import get_settings

        get_settings.cache_clear()

        from app.api.v1.legal import _pick_urls

        privacy, terms, resolved = _pick_urls("tc")
        self.assertEqual(privacy, "https://example.com/en-privacy")
        self.assertEqual(terms, "https://example.com/en-terms")
        self.assertEqual(resolved, "en")

    def test_pick_urls_tc_when_configured(self) -> None:
        os.environ["LEGAL_PRIVACY_URL_EN"] = "https://example.com/en-privacy"
        os.environ["LEGAL_TERMS_URL_EN"] = "https://example.com/en-terms"
        os.environ["LEGAL_PRIVACY_URL_TC"] = "https://example.com/tc-privacy"
        os.environ["LEGAL_TERMS_URL_TC"] = "https://example.com/tc-terms"

        from app.core.config import get_settings

        get_settings.cache_clear()

        from app.api.v1.legal import _pick_urls

        privacy, terms, resolved = _pick_urls("tc")
        self.assertEqual(privacy, "https://example.com/tc-privacy")
        self.assertEqual(terms, "https://example.com/tc-terms")
        self.assertEqual(resolved, "tc")


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

