from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from runtime_config import load_runtime_config


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Run flow14 livestream pipeline in one command.")
    p.add_argument("--python", default=sys.executable, help="Python executable path")
    p.add_argument("--config-source", choices=["yaml", "db"], default="db")
    p.add_argument("--config", default="", help="yaml path when config-source=yaml")
    p.add_argument("--config-table", default="cepconfiguration")
    p.add_argument("--config-key", default="vip-report")
    p.add_argument("--mysql-host", default="192.168.138.182")
    p.add_argument("--mysql-port", type=int, default=3306)
    p.add_argument("--mysql-user", default="ceptest")
    p.add_argument("--mysql-password", default="ck@123456")
    p.add_argument("--mysql-database", default="ckc_cep_db_test")
    p.add_argument("--download-dir", default=r"C:\vipdata")
    p.add_argument("--skip-compose", action="store_true", help="Only download/import/render 2 images, skip final compose")
    return p.parse_args()


def build_common_args(args: argparse.Namespace) -> list[str]:
    common = [
        "--config-source",
        args.config_source,
        "--config-table",
        args.config_table,
        "--config-key",
        args.config_key,
        "--mysql-host",
        args.mysql_host,
        "--mysql-port",
        str(args.mysql_port),
        "--mysql-user",
        args.mysql_user,
        "--mysql-password",
        args.mysql_password,
        "--mysql-database",
        args.mysql_database,
    ]
    if args.config_source == "yaml":
        config_path = args.config or str((SCRIPT_DIR.parent / "config.yaml").resolve())
        return ["--config", config_path]
    return common


def run_step(step_index: int, total: int, cmd: list[str]) -> None:
    print(f"[STEP {step_index}/{total}] {' '.join(cmd)}")
    result = subprocess.run(cmd, text=True, capture_output=True)
    if result.stdout:
        print(result.stdout)
    if result.returncode != 0:
        err = (result.stderr or "").strip()
        out = (result.stdout or "").strip()
        err_tail = err[-4000:] if len(err) > 4000 else err
        out_tail = out[-2000:] if len(out) > 2000 else out
        raise RuntimeError(
            "STEP_FAILED\n"
            f"step={step_index}\n"
            f"command={' '.join(cmd)}\n"
            f"returncode={result.returncode}\n"
            f"stdout_tail=\n{out_tail}\n"
            f"stderr_tail=\n{err_tail}\n"
        )


def main() -> None:
    args = parse_args()
    root = SCRIPT_DIR
    common = build_common_args(args)
    runtime_cfg = load_runtime_config(
        args,
        default_config=Path(args.config) if args.config else (root.parent / "config.yaml"),
    )
    workdir = Path(runtime_cfg["paths"]["workdir"]).resolve()

    steps: list[list[str]] = [
        [
            args.python,
            str(root / "sync_vis_live_session_downloads.py"),
            *common,
            "--download-dir",
            args.download_dir,
        ],
        [args.python, str(root / "load_vis_live_session_to_mysql.py"), *common],
        [args.python, str(root / "sync_cep_live_session_assets.py"), *common],
        [args.python, str(root / "sync_cep_live_session_trend_assets.py"), *common],
    ]

    if not args.skip_compose:
        steps.append(
            [
                args.python,
                str(root / "compose_live_session_report.py"),
                *common,
                "--summary-image",
                str(workdir / "assets" / "cep-live-session" / "cep-live-session-summary.png"),
                "--trend-image",
                str(workdir / "assets" / "cep-live-session" / "cep-live-session-sales-penetration-trend.png"),
                "--pivot-image",
                str(workdir / "assets" / "cep-live-goods-effect" / "cep-live-goods-effect-pivot.png"),
                "--output",
                str(workdir / "assets" / "cep-live-session" / "cep-live-session-combined.png"),
            ]
        )

    total = len(steps)
    for i, cmd in enumerate(steps, start=1):
        run_step(i, total, cmd)

    print(f"FINAL_IMAGE={workdir / 'assets' / 'cep-live-session' / 'cep-live-session-combined.png'}")
    print("FLOW14_PIPELINE_OK")


if __name__ == "__main__":
    main()

