"""
Main script for econometric analysis project walkthrough.

This script runs all build and analysis scripts in the correct order.
Sets the project root directory for all subsequent scripts.

Usage: cd into the project folder, then run:
    python main.py
"""

import os
import subprocess
import sys
from pathlib import Path

# Set project root directory
ROOT = Path(__file__).parent.resolve()

# Create output directories (zip may strip empty folders)
(ROOT / "build" / "output").mkdir(parents=True, exist_ok=True)
(ROOT / "analysis" / "output" / "tables").mkdir(parents=True, exist_ok=True)
(ROOT / "analysis" / "output" / "figures").mkdir(parents=True, exist_ok=True)

# Print header
print("=" * 80)
print("ECONOMETRIC ANALYSIS PROJECT - PYTHON WALKTHROUGH")
print("=" * 80)
print(f"\nProject root: {ROOT}\n")

# Define scripts to run in order
scripts = [
    # Build scripts
    "build/code/01_collapse_crashes.py",
    "build/code/02_collapse_demographics.py",
    "build/code/03_merge_datasets.py",

    # Analysis scripts
    "analysis/code/01_descriptive_table.py",
    "analysis/code/02_dd_regression.py",
    "analysis/code/03_event_study.py",
    "analysis/code/04_iv.py",
    "analysis/code/05_rd.py",
]

# Run each script
for i, script in enumerate(scripts, 1):
    script_path = ROOT / script

    print(f"\n{'=' * 80}")
    print(f"[{i}/{len(scripts)}] Running: {script}")
    print(f"{'=' * 80}\n")

    # Run script using subprocess
    result = subprocess.run(
        [sys.executable, str(script_path)],
        cwd=str(ROOT),
        env={**dict(os.environ), "PROJECT_ROOT": str(ROOT)},
        capture_output=False
    )

    # Check if script succeeded
    if result.returncode != 0:
        print(f"\n*** ERROR: Script {script} failed with return code {result.returncode} ***")
        sys.exit(1)

    print(f"\n✓ Completed: {script}")

# ─── Compile LaTeX tables to PDF ─────────────────────────────────────────────
import shutil

tables_dir = ROOT / "analysis" / "output" / "tables"
tex_files = sorted(tables_dir.glob("*.tex"))

if tex_files and shutil.which("pdflatex"):
    print(f"\n{'='*60}")
    print("COMPILING LATEX TABLES TO PDF")
    print(f"{'='*60}")
    for tex_file in tex_files:
        wrapper = tex_file.with_suffix(".compile.tex")
        wrapper.write_text(
            "\\documentclass[border=10pt]{standalone}\n"
            "\\usepackage{booktabs,amsmath,threeparttable,makecell}\n"
            "\\begin{document}\n"
            f"\\input{{{tex_file.name}}}\n"
            "\\end{document}\n"
        )
        result = subprocess.run(
            ["pdflatex", "-interaction=nonstopmode", wrapper.name],
            cwd=str(tables_dir),
            capture_output=True,
        )
        pdf_out = wrapper.with_suffix(".pdf")
        target = tex_file.with_suffix(".pdf")
        if pdf_out.exists():
            pdf_out.rename(target)
            print(f"  Compiled: {target.name}")
        else:
            print(f"  WARNING: Failed to compile {tex_file.name}")
        for ext in [".compile.tex", ".compile.aux", ".compile.log"]:
            f = tables_dir / (tex_file.stem + ext)
            if f.exists():
                f.unlink()
elif not tex_files:
    print("\nNo .tex files found — skipping PDF compilation.")
else:
    print("\npdflatex not found — skipping PDF compilation.")
    print("Install LaTeX to compile tables: https://www.tug.org/texlive/")

print("\n" + "=" * 80)
print("ALL SCRIPTS COMPLETED SUCCESSFULLY")
print("=" * 80)
