#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
One-command workspace reproduction.

Run from the workspace root:

    python run_pipeline.py

This orchestrates:
1. Unicode forensic reports from ornamented Excel files.
2. Normalized Excel/CSV/JSON outputs.
3. Ornamentation JSON exports from the original ornamented Excel files.

The child scripts are expected to be in the same folder as this file.
"""

from __future__ import annotations

import argparse
import shutil
import subprocess
import sys
from pathlib import Path


PIPELINE_STEPS = [
    {
        "name": "Unicode scan reports",
        "script_candidates": ["ornamentation_scanner_recursive.py", "ornamentation_scanner.py"],
        "args": ["--in-dir", ".", "--out-dir", "unicode_reports"],
        "output_dirs": ["unicode_reports"],
    },
    {
        "name": "Normalization engine",
        "script_candidates": ["normalization_engine_recursive.py", "normalization_engine.py"],
        "args": ["--in-dir", ".", "--out-dir", "normalized_outputs_all_with_json"],
        "output_dirs": ["normalized_outputs_all_with_json"],
    },
    {
        "name": "Ornamentation JSON export",
        "script_candidates": ["build_ornamentation_json.py", "_build_ornamentation_json.py"],
        "args": ["--in-dir", ".", "--out-dir", "ornamentation_json"],
        "output_dirs": ["ornamentation_json"],
    },
]


def find_script(root: Path, candidates: list[str]) -> Path:
    for name in candidates:
        path = root / name
        if path.exists():
            return path
    raise FileNotFoundError(f"None of these scripts were found: {', '.join(candidates)}")


def remove_outputs(root: Path) -> None:
    for step in PIPELINE_STEPS:
        for folder in step["output_dirs"]:
            path = root / folder
            if path.exists():
                shutil.rmtree(path)
                print(f"[CLEAN] removed {path}")


def run_step(root: Path, step: dict, python_exe: str) -> None:
    script = find_script(root, step["script_candidates"])
    cmd = [python_exe, str(script), *step["args"]]

    print(f"\n=== {step['name']} ===")
    print(" ".join(cmd))

    result = subprocess.run(cmd, cwd=root)
    if result.returncode != 0:
        raise SystemExit(result.returncode)


def main() -> None:
    ap = argparse.ArgumentParser(description="Run the full normalization / ornamentation pipeline.")
    ap.add_argument("--clean", action="store_true", help="Delete generated output folders before running.")
    ap.add_argument("--skip-scan", action="store_true", help="Skip Unicode scan reports.")
    ap.add_argument("--skip-normalize", action="store_true", help="Skip normalized output generation.")
    ap.add_argument("--skip-ornamentation-json", action="store_true", help="Skip ornamentation JSON export.")
    args = ap.parse_args()

    root = Path(__file__).resolve().parent
    python_exe = sys.executable

    if args.clean:
        remove_outputs(root)

    for step in PIPELINE_STEPS:
        name = step["name"].lower()
        if args.skip_scan and "unicode" in name:
            continue
        if args.skip_normalize and "normalization" in name:
            continue
        if args.skip_ornamentation_json and "ornamentation json" in name:
            continue
        run_step(root, step, python_exe)

    print("\nPipeline complete.")


if __name__ == "__main__":
    main()
