#!/usr/bin/env python3
"""
Kitzu — Master Data Collection Pipeline

Runs all collectors and generates the daily brief.
This is the single command that pulls everything together.

Usage:
    python3 collect_all.py              # Run all collectors + generate brief
    python3 collect_all.py --status     # Show data lake status
    python3 collect_all.py --brief-only # Skip collection, just generate brief
"""

import sys
import subprocess
import argparse
from pathlib import Path
from datetime import datetime

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

def run(script: str, args: list = None, label: str = ""):
    """Run a collector script and capture output."""
    cmd = [sys.executable, str(KITZU_ROOT / script)] + (args or [])
    print(f"\n{'='*50}")
    print(f"  {label or script}")
    print(f"{'='*50}")
    result = subprocess.run(cmd, capture_output=False, text=True)
    return result.returncode == 0


def main():
    parser = argparse.ArgumentParser(description="Kitzu Master Collection Pipeline")
    parser.add_argument("--status", action="store_true", help="Show data lake status")
    parser.add_argument("--brief-only", action="store_true", help="Skip collection, just brief")
    parser.add_argument("--backfill", type=int, help="Backfill N days of Oura data")
    args = parser.parse_args()

    if args.status:
        run("schema.py", label="Data Lake Status")
        return

    start = datetime.now()
    print(f"\nKitzu Collection Pipeline — {start.strftime('%Y-%m-%d %H:%M')}")
    print(f"{'='*50}")

    if not args.brief_only:
        # 1. Oura (daily wearable data)
        oura_args = []
        if args.backfill:
            oura_args = ["--backfill", str(args.backfill)]
        run("collectors/collect_oura.py", oura_args, label="Oura Ring Collector")

        # 2. Blood biomarkers (from InsideTracker dashboard-data.json)
        run("collectors/collect_blood.py", label="Blood Biomarker Collector")

        # 3. iHealth vitals — BP, weight, body composition
        run("collectors/collect_ihealth.py", label="iHealth Vitals Collector")

        # Future collectors (uncomment as built):
        # run("collectors/collect_23andme.py", label="23andMe Genetics")
        # run("collectors/collect_viome.py", label="Viome Microbiome")
        # run("collectors/collect_cgm.py", label="CGM Glucose Data")

    # 3. Generate daily brief
    run("engine/daily_brief.py", ["--save"], label="Daily Brief Engine")

    elapsed = (datetime.now() - start).total_seconds()
    print(f"\n{'='*50}")
    print(f"  Pipeline complete in {elapsed:.1f}s")
    print(f"{'='*50}\n")


if __name__ == "__main__":
    main()
