from __future__ import annotations

import json
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path


PROJECT_ROOT = Path(__file__).resolve().parents[1]
BUILDER = PROJECT_ROOT / "company_reports" / "xlsx" / "build_workbook.mjs"
FIXTURE = (
    PROJECT_ROOT
    / "tests"
    / "fixtures"
    / "company_reports"
    / "synthetic_qbd_payload.json"
)
ARTIFACT_PACKAGE = (
    PROJECT_ROOT
    / "company_reports"
    / "xlsx"
    / "node_modules"
    / "@oai"
    / "artifact-tool"
)


def artifact_tool_available() -> bool:
    configured = os.environ.get("COMPANY_REPORT_ARTIFACT_TOOL_MODULE", "").strip()
    return ARTIFACT_PACKAGE.exists() or bool(configured and Path(configured).is_file())


def node_binary() -> str:
    configured = os.environ.get("COMPANY_REPORT_NODE_BINARY", "").strip()
    return configured or shutil.which("node") or ""


@unittest.skipUnless(artifact_tool_available(), "artifact-tool dependency is not installed")
class CompanyReportXlsxTests(unittest.TestCase):
    def test_builder_exports_reopens_checks_and_renders_all_sheets(self):
        node = node_binary()
        if not node:
            self.skipTest("Node.js is unavailable")
        with tempfile.TemporaryDirectory(prefix="company-report-xlsx-test-") as temp_dir:
            root = Path(temp_dir)
            output = root / "QBD-July-2026.xlsx"
            previews = root / "previews"
            summary_path = root / "summary.json"
            completed = subprocess.run(
                [
                    node,
                    str(BUILDER),
                    str(FIXTURE),
                    str(output),
                    str(previews),
                    str(summary_path),
                ],
                cwd=PROJECT_ROOT,
                capture_output=True,
                text=True,
                timeout=90,
                check=False,
            )

            self.assertEqual(completed.returncode, 0, completed.stderr)
            self.assertTrue(output.is_file())
            self.assertFalse(Path(f"{output}.inspect.ndjson").exists())
            self.assertEqual(output.stat().st_mode & 0o777, 0o600)
            summary = json.loads(summary_path.read_text(encoding="utf-8"))
            self.assertEqual(summary["status"], "success")
            self.assertEqual(summary["row_counts"], [2, 1, 0])
            self.assertEqual(summary["formula_count"], 0)
            self.assertEqual(summary["preview_count"], 3)
            self.assertEqual(len(list(previews.glob("sheet-*.png"))), 3)

    def test_invalid_payload_fails_with_only_a_stable_error_code(self):
        node = node_binary()
        if not node:
            self.skipTest("Node.js is unavailable")
        with tempfile.TemporaryDirectory(prefix="company-report-xlsx-test-") as temp_dir:
            root = Path(temp_dir)
            invalid = root / "invalid.json"
            invalid.write_text(
                json.dumps({"schema_version": "invalid", "synthetic_marker": "SYN-ONLY"}),
                encoding="utf-8",
            )
            completed = subprocess.run(
                [
                    node,
                    str(BUILDER),
                    str(invalid),
                    str(root / "invalid.xlsx"),
                    str(root / "previews"),
                    str(root / "summary.json"),
                ],
                cwd=PROJECT_ROOT,
                capture_output=True,
                text=True,
                timeout=30,
                check=False,
            )

            self.assertEqual(completed.returncode, 4)
            self.assertEqual(
                json.loads(completed.stderr),
                {
                    "status": "failed",
                    "code": "COMPANY_REPORT_OUTPUT_VALIDATION_FAILED",
                },
            )
            self.assertNotIn("SYN-ONLY", completed.stderr)
            self.assertFalse((root / "invalid.xlsx").exists())


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