from __future__ import annotations

import csv
import time
from datetime import datetime
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = BASE_DIR / "outputs"
RUNTIME_LOG = OUTPUT_DIR / "runtime_log.csv"


def timed_main(script_name: str, func):
    start = time.perf_counter()
    try:
        return func()
    finally:
        elapsed = time.perf_counter() - start
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        write_header = not RUNTIME_LOG.exists()
        with RUNTIME_LOG.open("a", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(
                f,
                fieldnames=["timestamp", "script", "runtime_seconds"],
            )
            if write_header:
                writer.writeheader()
            writer.writerow(
                {
                    "timestamp": datetime.now().isoformat(timespec="seconds"),
                    "script": script_name,
                    "runtime_seconds": f"{elapsed:.6f}",
                }
            )
        print(f"Runtime for {script_name}: {elapsed:.3f} seconds")
