#!/usr/bin/env python3
"""Run the complete MACStats download, profile, tidy, and validation workflow."""

from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path


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


def run(script: str, *extra: str) -> None:
    command = [sys.executable, str(PROJECT_ROOT / "src" / script), "--project-root", str(PROJECT_ROOT), *extra]
    print("\n$ " + " ".join(command), flush=True)
    subprocess.run(command, cwd=PROJECT_ROOT, check=True)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--skip-download", action="store_true", help="Reuse the existing source manifest and downloads.")
    parser.add_argument("--force-download", action="store_true", help="Redownload every source file and replace the local copy.")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    if args.force_download and args.skip_download:
        raise SystemExit("--force-download and --skip-download cannot be used together")
    if not args.skip_download:
        run("download_sources.py", *(["--force"] if args.force_download else []))
    run("profile_workbooks.py")
    run("build_tidy.py")
    run("validate_outputs.py")


if __name__ == "__main__":
    main()
