from django.test import TestCase
from .stock.stock_utils import tscodeCheck, date_format_correction, get_released_report_dates


class TscodeCheckTest(TestCase):
    """股票代码格式校验测试"""

    def test_sz_6digit(self):
        self.assertEqual(tscodeCheck('000001'), '000001.SZ')

    def test_sz_6digit_300(self):
        self.assertEqual(tscodeCheck('300750'), '300750.SZ')

    def test_sh_6digit_60(self):
        self.assertEqual(tscodeCheck('600000'), '600000.SH')

    def test_sh_6digit_68(self):
        self.assertEqual(tscodeCheck('688001'), '688001.SH')

    def test_bj_6digit(self):
        self.assertEqual(tscodeCheck('830799'), '830799.BJ')

    def test_9digit_pass_through(self):
        self.assertEqual(tscodeCheck('000001.SZ'), '000001.SZ')

    def test_lowercase_to_uppercase(self):
        self.assertEqual(tscodeCheck('000001.sz'), '000001.SZ')

    def test_invalid_length_short(self):
        with self.assertRaises(ValueError):
            tscodeCheck('12345')

    def test_invalid_length_long(self):
        with self.assertRaises(ValueError):
            tscodeCheck('1234567890')

    def test_invalid_suffix(self):
        with self.assertRaises(ValueError):
            tscodeCheck('000001.XX')

    def test_not_string(self):
        with self.assertRaises(ValueError):
            tscodeCheck(123456)

    def test_unknown_prefix(self):
        with self.assertRaises(ValueError):
            tscodeCheck('500001')


class DateFormatCorrectionTest(TestCase):
    """日期格式校正测试"""

    def test_yyyymmdd_passthrough(self):
        self.assertEqual(date_format_correction('20240115'), '20240115')

    def test_yyyy_mm_dd_conversion(self):
        self.assertEqual(date_format_correction('2024-01-15'), '20240115')

    def test_invalid_format(self):
        self.assertIsNone(date_format_correction('15/01/2024'))

    def test_empty_string(self):
        self.assertIsNone(date_format_correction(''))


class GetReleasedReportDatesTest(TestCase):
    """财报发布日期测试"""

    def test_returns_list(self):
        result = get_released_report_dates('20230101', '20231231')
        self.assertIsInstance(result, list)

    def test_all_dates_yyyymmdd_format(self):
        result = get_released_report_dates('20230101', '20231231')
        for d in result:
            self.assertEqual(len(d), 8)
            self.assertTrue(d.isdigit())

    def test_start_after_end_returns_empty(self):
        result = get_released_report_dates('20251231', '20230101')
        self.assertEqual(result, [])

    def test_single_year_quarters(self):
        """单年内应该返回最多4个季末日期"""
        result = get_released_report_dates('20200101', '20201231')
        for d in result:
            self.assertTrue(d.endswith(('0331', '0630', '0930', '1231')))
