from __future__ import annotations

import unittest

from backend.data.providers.ifind_client import IfindError, IfindHttpClient


class IfindClientTests(unittest.TestCase):
    def test_table_rows_normalizes_single_table_payload(self):
        rows = IfindHttpClient._table_rows(
            {
                "tables": {
                    "thscode": "300033.SZ",
                    "time": ["2026-07-28 09:30", "2026-07-28 09:31"],
                    "table": {"close": [10.1, 10.2], "amount": [100, 200]},
                }
            }
        )

        self.assertEqual(len(rows), 2)
        self.assertEqual(rows[0]["thscode"], "300033.SZ")
        self.assertEqual(rows[1]["time"], "2026-07-28 09:31")
        self.assertEqual(rows[1]["close"], 10.2)

    def test_table_rows_normalizes_wencai_list_payload(self):
        rows = IfindHttpClient._table_rows(
            {
                "tables": [
                    {
                        "table": {
                            "股票代码": ["000001.SZ", "600000.SH"],
                            "股票简称": ["平安银行", "浦发银行"],
                        }
                    }
                ]
            }
        )

        self.assertEqual([row["股票代码"] for row in rows], ["000001.SZ", "600000.SH"])

    def test_display_date_rejects_invalid_values(self):
        self.assertEqual(IfindHttpClient._display_date("20260728"), "2026-07-28")
        with self.assertRaises(IfindError):
            IfindHttpClient._display_date("2026-7-28")

    def test_client_requires_credentials_before_request(self):
        client = IfindHttpClient()
        self.assertFalse(client.configured)
        with self.assertRaises(IfindError):
            client.real_time("000001.SH", ["latest"])


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