"""
Demo launcher — does everything the .bat tries to do, but in Python where
parser quirks can't bite. Run via Start_Demo.bat (Windows) or directly:

    python launcher.py
"""
from __future__ import annotations

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

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


def banner(text: str):
    line = "=" * 60
    print(line)
    print(f"  {text}")
    print(line)


def run(cmd, **kw):
    """Run a subprocess, stream output, return exit code."""
    print(f">>> {' '.join(cmd) if isinstance(cmd, (list, tuple)) else cmd}")
    return subprocess.call(cmd, cwd=HERE, **kw)


def hold_open():
    """Wait for Enter so the window does not vanish."""
    try:
        input("\nPress Enter to close...")
    except (EOFError, KeyboardInterrupt):
        pass


def main() -> int:
    os.chdir(HERE)
    banner("Demand Planning Demo")
    print(f"Folder: {HERE}")
    print(f"Python: {sys.version.split()[0]}  ({sys.executable})")
    print()

    # Sanity check Python version
    if sys.version_info >= (3, 13):
        print("[WARN] You are on Python 3.13+. Some packages (scipy, statsforecast)")
        print("       may not have wheels yet. Recommended: Python 3.12.")
        print("       Continuing anyway — pip will tell us if it can't build.\n")

    # Ensure pip is available
    try:
        import pip  # noqa: F401
    except ImportError:
        print("[ERROR] pip is missing. Reinstall Python with pip enabled.")
        hold_open()
        return 1

    # Install requirements if streamlit is missing
    try:
        import streamlit  # noqa: F401
    except ImportError:
        banner("Installing dependencies (~2 min, first run only)")
        rc = run([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        rc = run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        if rc != 0:
            print("\n[ERROR] pip install failed. Most common cause:")
            print("  - You are on Python 3.13/3.14 — install Python 3.12 instead.")
            print("  - Network blocked — check internet / proxy.")
            hold_open()
            return rc

    # Generate demo data if missing
    if not (HERE / "data" / "sales_clean.csv").exists():
        banner("Generating dummy data")
        rc = run([sys.executable, "generate_demo_data.py"])
        if rc != 0:
            hold_open()
            return rc

    # Build initial forecast workbook if missing
    plan_xlsx = HERE / "data" / "Polleo_Demand_Plan.xlsx"
    if not plan_xlsx.exists():
        banner("Building initial forecast (~60s)")
        rc = run([sys.executable, "build_initial_forecast.py"])
        if rc != 0:
            print("[WARN] forecast build failed — app still launches; click")
            print("       'Run forecast' from the sidebar to build it later.\n")

    # Launch Streamlit (blocking)
    banner("Launching Streamlit at http://localhost:8501")
    print("Press Ctrl+C in this window to stop.\n")
    rc = run([sys.executable, "-m", "streamlit", "run", "app.py"])

    print()
    banner(f"Streamlit exited (code {rc})")
    hold_open()
    return rc


if __name__ == "__main__":
    sys.exit(main())
