from __future__ import annotations

import json
import tempfile
import unittest
from datetime import date
from pathlib import Path
from typing import Optional

from monthly_reports.contracts import ErrorCode, MonthlySnapshot
from monthly_reports.core import build_monthly_report
from monthly_reports.publishing import (
    AtomicReportPublisher,
    BuiltWorkbook,
    PublicationError,
    sha256_file,
)
from monthly_reports.repository import FileMetadata, RepositoryError, ReservedReport


class FakeRepository:
    def __init__(self, fail_activation: bool = False):
        self.fail_activation = fail_activation
        self.activated: Optional[tuple] = None
        self.failed: Optional[tuple] = None

    def activate_report(self, reservation, artifact, result_json, semantic_sha256) -> None:
        if self.fail_activation:
            raise RepositoryError(ErrorCode.PUBLISH_FAILED, "synthetic activation failed")
        self.activated = (reservation, artifact, result_json, semantic_sha256)

    def mark_failed(self, reservation, code: str, safe_message: str) -> None:
        self.failed = (reservation, code, safe_message)


def empty_report():
    return build_monthly_report(
        2026,
        7,
        date(2026, 7, 26),
        MonthlySnapshot((), (), ()),
    )


class MonthlyReportsPublishingTests(unittest.TestCase):
    def test_publish_retains_immutable_version_and_updates_latest(self):
        with tempfile.TemporaryDirectory(prefix="monthly-report-publish-") as temp_dir:
            project_root = Path(temp_dir) / "project"
            output_root = project_root / "outputs" / "monthly_reports"
            work_dir = project_root / "staging"
            month_root = output_root / "2026" / "07"
            work_dir.mkdir(parents=True)
            month_root.mkdir(parents=True)
            latest = month_root / "latest.xlsx"
            latest_result = month_root / "latest.result.json"
            latest.write_bytes(b"synthetic-old-workbook")
            latest_result.write_text('{"status":"old"}\n', encoding="utf-8")
            report = empty_report()
            built_path = work_dir / report.filename
            built_path.write_bytes(b"synthetic-new-workbook")
            built = BuiltWorkbook(
                built_path,
                sha256_file(built_path),
                built_path.stat().st_size,
                {"semantic_sha256": "c" * 64},
            )
            reservation = ReservedReport(44, 2)
            repository = FakeRepository()

            outcome = AtomicReportPublisher(project_root, output_root).publish(
                report,
                reservation,
                built,
                repository,
                work_dir,
            )

            self.assertEqual(latest.read_bytes(), b"synthetic-new-workbook")
            self.assertEqual(outcome.archive_path.read_bytes(), b"synthetic-new-workbook")
            result = json.loads(outcome.result_path.read_text(encoding="utf-8"))
            self.assertEqual(result["report_version_id"], 44)
            self.assertEqual(result["row_count"], 0)
            self.assertEqual(len(result["channel_manifest"]), 5)
            self.assertEqual(
                json.loads(latest_result.read_text(encoding="utf-8"))["version_no"],
                2,
            )
            self.assertEqual(outcome.archive_path.stat().st_mode & 0o777, 0o600)
            self.assertIsNotNone(repository.activated)
            self.assertIsNone(repository.failed)

    def test_activation_failure_restores_latest_and_removes_new_archive(self):
        with tempfile.TemporaryDirectory(prefix="monthly-report-publish-") as temp_dir:
            project_root = Path(temp_dir) / "project"
            output_root = project_root / "outputs" / "monthly_reports"
            work_dir = project_root / "staging"
            month_root = output_root / "2026" / "07"
            work_dir.mkdir(parents=True)
            month_root.mkdir(parents=True)
            latest = month_root / "latest.xlsx"
            latest_result = month_root / "latest.result.json"
            latest.write_bytes(b"synthetic-old-workbook")
            latest_result.write_text('{"status":"old"}\n', encoding="utf-8")
            report = empty_report()
            built_path = work_dir / report.filename
            built_path.write_bytes(b"synthetic-new-workbook")
            built = BuiltWorkbook(
                built_path,
                sha256_file(built_path),
                built_path.stat().st_size,
                {"semantic_sha256": "c" * 64},
            )
            reservation = ReservedReport(45, 3)
            repository = FakeRepository(fail_activation=True)

            with self.assertRaises(PublicationError) as caught:
                AtomicReportPublisher(project_root, output_root).publish(
                    report,
                    reservation,
                    built,
                    repository,
                    work_dir,
                )

            self.assertEqual(caught.exception.code, ErrorCode.PUBLISH_FAILED)
            self.assertEqual(latest.read_bytes(), b"synthetic-old-workbook")
            self.assertEqual(latest_result.read_text(encoding="utf-8"), '{"status":"old"}\n')
            version_root = month_root / "archive" / "v0003"
            self.assertFalse((version_root / report.filename).exists())
            self.assertFalse((version_root / "result.json").exists())
            self.assertEqual(repository.failed[0], reservation)


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