"""
Generate the initial Polleo_Demand_Plan.xlsx for the demo bundle.

Runs forecast_engine.run() against the dummy data in ./data/ so the
demand-planning, revenue and supply pages have something to display
the moment the user launches the demo, without having to click
"Run forecast" first.

Idempotent — safe to re-run. Will overwrite any existing
data/Polleo_Demand_Plan.xlsx.

Skips silently if statsforecast / scikit-learn aren't installed
(the engine needs them); user can still click Run Forecast in the
app once dependencies arrive.
"""
from __future__ import annotations

import os
import sys
from pathlib import Path

DEMO = Path(__file__).parent
DATA = DEMO / "data"

# Engine requires an input_file path. It only opens that file if
# sku_plan_list.csv is missing — which it isn't in the demo. So we just
# create an empty placeholder workbook for it to point at.
PLACEHOLDER = DATA / "Polleo_Demand_Planning_Book.xlsx"


def ensure_placeholder():
    if PLACEHOLDER.exists():
        return
    try:
        from openpyxl import Workbook
        wb = Workbook()
        ws = wb.active
        ws.title = "Run Rate"
        ws.cell(1, 1, "Demo placeholder — engine reads sku_plan_list.csv directly")
        wb.save(PLACEHOLDER)
    except Exception as e:
        print(f"  WARN: could not create placeholder: {e}")


def main():
    if not (DATA / "sku_plan_list.csv").exists():
        print("  ERROR: data/sku_plan_list.csv missing. Run generate_demo_data.py first.")
        sys.exit(1)

    ensure_placeholder()

    # Engine resolves cwd-relative paths via os.path.dirname(input_file).
    # cd into Demo so all relative writes land in ./data.
    os.chdir(DEMO)

    try:
        import forecast_engine
    except ImportError as e:
        missing = str(e)
        print(f"  Skipping initial forecast — {missing}.")
        print("  Install requirements first: pip install -r requirements.txt")
        sys.exit(0)

    print(f"\n  Building initial forecast against dummy data...")
    forecast_engine.run(input_file=str(PLACEHOLDER))
    out = DATA / "Polleo_Demand_Plan.xlsx"
    if out.exists():
        kb = out.stat().st_size // 1024
        print(f"\n  OK — {out.name} written ({kb:,} KB)")
    else:
        print(f"\n  WARN — {out.name} not produced. Engine may have failed silently.")


if __name__ == "__main__":
    main()
