from __future__ import annotations

import tempfile
import unittest
from datetime import date
from decimal import Decimal
from pathlib import Path

from openpyxl import load_workbook

from monthly_reports.contracts import (
    ChannelObservation,
    DailyVersionPin,
    MonthlyFact,
    MonthlySnapshot,
)
from monthly_reports.core import build_monthly_report
from monthly_reports.publishing import OpenpyxlWorkbookBuilder


def report_fixture():
    source = MonthlyFact(
        daily_record_id=1,
        daily_version_id=100,
        business_date=date(2026, 7, 8),
        channel_key="QBD",
        arrival=date(2026, 7, 8),
        departure=date(2026, 7, 10),
        nights=2,
        adults=2,
        children=0,
        block_code="=SYN-FORMULA-LIKE",
        no_of_rooms=1,
        company_name="SYN-COMPANY",
        confirmation_no="SYN-CONFIRMATION",
        disp_room_no="SYN-ROOM",
        effective_rate_amount=Decimal("450.50"),
        full_name="SYN-GUEST",
        res_comment="SYN-COMMENT",
        trace_text="",
        products="",
        rate_code="SYN-RATE",
        room_category_label="SYN-TYPE",
        real_price=Decimal("450.50"),
        total_price=Decimal("901.00"),
        kb_amount=None,
    )
    return build_monthly_report(
        2026,
        7,
        date(2026, 7, 8),
        MonthlySnapshot(
            (source,),
            (DailyVersionPin(date(2026, 7, 8), 100),),
            (ChannelObservation(date(2026, 7, 8), 100, "QBD", 1, 1),),
        ),
    )


class MonthlyReportsXlsxTests(unittest.TestCase):
    def test_openpyxl_builder_reopens_checks_formulas_and_semantic_identity(self):
        report = report_fixture()
        with tempfile.TemporaryDirectory(prefix="monthly-report-xlsx-") as temp_dir:
            built = OpenpyxlWorkbookBuilder().build(report, Path(temp_dir))

            self.assertTrue(built.path.is_file())
            self.assertEqual(built.path.stat().st_mode & 0o777, 0o600)
            self.assertEqual(built.summary["sheet_names"][:5], [
                "LIANTAI-GROUP", "LIANTAI-FIT", "QBD", "DY-AI-Easy-KB", "FENGRUN"
            ])
            self.assertEqual(built.summary["row_counts"], [0, 0, 1, 0, 0])
            self.assertEqual(built.summary["formula_count"], 1)
            self.assertEqual(built.summary["preview_count"], 5)
            self.assertEqual(len(built.summary["semantic_sha256"]), 64)

            workbook = load_workbook(built.path, data_only=False, read_only=True)
            try:
                self.assertEqual(workbook["QBD"]["S2"].value, "=R2*C2*G2")
                self.assertEqual(workbook["QBD"]["F2"].value, "'=SYN-FORMULA-LIKE")
                formulas = [
                    cell.value
                    for sheet in workbook.worksheets
                    for row in sheet.iter_rows()
                    for cell in row
                    if cell.data_type == "f"
                ]
                self.assertEqual(formulas, ["=R2*C2*G2"])
            finally:
                workbook.close()


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