#!/usr/bin/env python3
"""Rebuild the BEA extraction and all F01 processed tables/figures.

No network access is used. The command expects the frozen raw files to be
present and verifies their hashes inside run_pipeline.py before analysis.
"""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path


ANALYSIS = Path(__file__).resolve().parent


def resolve_node() -> str:
    explicit = os.environ.get("F01_NODE_BIN", "").strip()
    candidates = [explicit, shutil.which("node") or ""]
    for candidate in candidates:
        if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK):
            return candidate
    raise RuntimeError("Node.js is required for the audited XLSX extraction; set F01_NODE_BIN to an executable Node binary.")


def main() -> None:
    node = resolve_node()
    subprocess.run([node, str(ANALYSIS / "extract_bea.mjs")], cwd=ANALYSIS.parent.parent.parent.parent, check=True)
    subprocess.run([sys.executable, str(ANALYSIS / "run_pipeline.py")], cwd=ANALYSIS.parent.parent.parent.parent, check=True)


if __name__ == "__main__":
    main()
