"""instance_display_prefs_lib 与 env_file_lib 单元测试."""
from __future__ import annotations

import os
import tempfile
import unittest

from lib.env.env_file_lib import apply_env_updates, env_get, read_env_lines
from lib.env.env_schema import parse_env_example_schema, validate_env_updates
from lib.instance.instance_display_prefs_lib import normalize_display_prefs, tab_allowed


class TestInstanceDisplayPrefs(unittest.TestCase):
    def test_normalize_defaults_all_on(self):
        prefs = normalize_display_prefs({})
        self.assertTrue(prefs["show_nav_env_config"])
        self.assertTrue(prefs["show_settings_password"])
        self.assertFalse(prefs["show_nav_dashboard"])

    def test_tab_allowed_respects_prefs(self):
        prefs = normalize_display_prefs({"show_nav_stats": False})
        self.assertFalse(tab_allowed("stats", prefs))
        self.assertTrue(tab_allowed("trade", prefs))

    def test_dashboard_nav_default_off(self):
        prefs = normalize_display_prefs({})
        self.assertFalse(tab_allowed("dashboard", prefs))
        on = normalize_display_prefs({"show_nav_dashboard": True})
        self.assertTrue(tab_allowed("dashboard", on))


class TestEnvFileLib(unittest.TestCase):
    def test_upsert_and_read(self):
        with tempfile.TemporaryDirectory() as td:
            path = os.path.join(td, ".env")
            with open(path, "w", encoding="utf-8") as f:
                f.write("FOO=1\n")
            changed = apply_env_updates(path, {"FOO": "2", "BAR": "x"})
            self.assertIn("FOO", changed)
            self.assertIn("BAR", changed)
            lines = read_env_lines(path)
            self.assertEqual(env_get(lines, "FOO"), "2")
            self.assertEqual(env_get(lines, "BAR"), "x")


class TestEnvSchema(unittest.TestCase):
    def test_parse_okx_example(self):
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        example = os.path.join(root, "crypto_monitor_okx", ".env.example")
        if not os.path.isfile(example):
            self.skipTest("missing okx .env.example")
        groups = parse_env_example_schema(example)
        keys = [f["key"] for g in groups for f in g.get("fields", [])]
        self.assertIn("OKX_API_KEY", keys)
        self.assertIn("MAX_ACTIVE_POSITIONS", keys)

    def test_validate_unknown_key(self):
        groups = [{"title": "t", "fields": [{"key": "A", "type": "text", "sensitive": False}]}]
        clean, errors = validate_env_updates(groups, {"B": "1"})
        self.assertTrue(errors)


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