from __future__ import annotations

import unittest

from tushare_client import TushareClient


class HotMoneyProfileClient(TushareClient):
    def query(self, api_name, params=None, fields=""):
        self.last_request = (api_name, params or {}, fields)
        if api_name != "hm_list":
            raise AssertionError(f"unexpected api: {api_name}")
        return [
            {
                "name": "赵老哥",
                "desc": "聚焦市场核心标的。",
                "orgs": "华泰证券浙江分公司；银河证券绍兴",
            },
            {
                "name": "炒股养家",
                "desc": "",
                "orgs": "华鑫证券上海宛平南路, 华鑫证券上海分公司",
            },
            {
                "name": "赵老哥",
                "desc": "重复记录不应覆盖首条档案。",
                "orgs": "重复席位",
            },
            {"name": "", "desc": "无效记录", "orgs": ""},
        ]


class HotMoneyProfileTests(unittest.TestCase):
    def test_directory_normalizes_profiles_and_organizations(self):
        client = HotMoneyProfileClient("token")
        payload = client.hot_money_profiles()

        self.assertEqual(client.last_request[0], "hm_list")
        self.assertEqual(client.last_request[2], "name,desc,orgs")
        self.assertEqual(payload["meta"]["status"], "success")
        self.assertEqual(payload["summary"], {
            "profile_count": 2,
            "described_count": 1,
            "organization_count": 4,
        })
        self.assertEqual(
            payload["profiles"][0]["organizations"],
            ["华泰证券浙江分公司", "银河证券绍兴"],
        )
        self.assertEqual(payload["profiles"][1]["organization_count"], 2)
        self.assertEqual(
            [item["id"] for item in payload["profiles"]],
            ["hot-money-profile-1", "hot-money-profile-2"],
        )

    def test_directory_parses_json_encoded_organization_lists(self):
        client = TushareClient("token")
        client.query = lambda *_args, **_kwargs: [
            {
                "name": "Profile",
                "desc": "",
                "orgs": '["Seat A", "Seat B", "Seat A"]',
            }
        ]

        payload = client.hot_money_profiles()

        self.assertEqual(payload["profiles"][0]["organizations"], ["Seat A", "Seat B"])
        self.assertEqual(payload["summary"]["organization_count"], 2)


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