#!/usr/bin/env python3
"""
Project wrapper: runs the 1688-bp-watch-enrich recipe for the 22 conf-3+
leads surfaced by the longlist pass. Passes the project's
stage2_offer_ids.json (the 22 offer ids) and stage2_targets.json (the
offer-id → lead_id map) into the recipe.

This is a thin wrapper. The recipe lives in
`~/.openclaw/apify/recipes/1688-bp-watch-enrich.py`.

Usage:
    export APIFY_TOKEN=*** -c 'import json; print(json.load(open("/home/claw/.openclaw/credentials/apify.json"))["token"])')
    python3 apify_enrich.py [--max-cost USD] [--dry-run] [--no-sync]
"""

import argparse
import csv
import re
import shutil
import subprocess
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parent
RECIPE = "1688-bp-watch-enrich"
PROJECT_NAME = "pneumatic-wrist-leads"
TARGETS_JSON = PROJECT / "stage2_offer_ids.json"
LEAD_MAP_JSON = PROJECT / "stage2_targets.json"
LOCAL_ENRICHED = PROJECT / "stage2_enriched.csv"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--max-cost", type=float, default=0.50)
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--no-sync", action="store_true",
                    help="don't copy the new enriched.csv into the project dir")
    args = ap.parse_args()

    cli = ["/home/claw/bin/apify", "run", RECIPE,
           "--project", PROJECT_NAME,
           "--max-cost", str(args.max_cost),
           "--targets", str(TARGETS_JSON),
           "--lead-map", str(LEAD_MAP_JSON)]
    if args.dry_run:
        cli.append("--dry-run")
    print(f"$ {' '.join(cli)}", flush=True)
    rc = subprocess.call(cli)
    if rc != 0 or args.dry_run or args.no_sync:
        return rc

    # Find the latest enriched.csv under the recipe's datasets dir
    base = Path.home() / ".openclaw/apify" / "datasets" / PROJECT_NAME / RECIPE
    if not base.exists():
        print("warning: no run output found; skipping sync", file=sys.stderr)
        return 0
    runs = sorted([p for p in base.iterdir() if p.is_dir()], reverse=True)
    latest = None
    for r in runs:
        c = r / "enriched.csv"
        if c.exists():
            latest = c
            break
    if not latest:
        print("warning: no enriched.csv in any run; skipping sync", file=sys.stderr)
        return 0
    shutil.copy(latest, LOCAL_ENRICHED)
    print(f"synced {latest} → {LOCAL_ENRICHED}")
    return 0


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