"""Spin up a brand-new launch from a name. The Ep 15 'Your Turn' teaser.

Default --dry-run. Pass --apply to actually create rows.

Creates:
  - 1 lc_launch row (Planning, target +90 days)
  - 5 starter milestones spaced 14 days apart
  - 1 'Launch initialized' status update tagged SpinUp::

Designed to complete in <5 sec on camera.

Use:
  python episodes/ep-15-full-orchestra/orchestra/spin_up_launch.py "Q4 Holiday Feature"
  python episodes/ep-15-full-orchestra/orchestra/spin_up_launch.py "Q4 Holiday Feature" --apply
"""
from __future__ import annotations
import argparse, os, sys
from datetime import datetime, timedelta, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _common import DV, LAUNCH_STATUS, MILESTONE_STATUS  # noqa: E402

STARTER_MILESTONES = [
    "Discovery & scoping",
    "Engineering build",
    "Internal beta",
    "GA readiness review",
    "Public launch",
]


def main() -> int:
    p = argparse.ArgumentParser()
    p.add_argument('name', help='Name for the new launch (e.g. "Q4 Holiday Feature")')
    g = p.add_mutually_exclusive_group()
    g.add_argument('--dry-run', action='store_true', default=True)
    g.add_argument('--apply', action='store_true')
    args = p.parse_args()
    dry = not args.apply

    dv = DV(dry_run=dry)
    print(f"[{'DRY RUN' if dry else 'APPLY'}] spin up new launch: {args.name}")
    print(f"  env: {dv.url}")

    today = datetime.now(timezone.utc).date()
    target = today + timedelta(days=90)
    launch_body = {
        'lc_name': args.name,
        'lc_launchstatus': LAUNCH_STATUS['Planning'],
        'lc_targetdate': target.isoformat(),
        'lc_description': f"Auto-generated by spin_up_launch.py on {today.isoformat()}",
    }
    odata_id = dv.post("/api/data/v9.2/lc_launchs", launch_body, label='create launch')
    if dry:
        lid = '<would-be-launchid>'
    else:
        lid = (odata_id or '').rsplit('(', 1)[-1].rstrip(')')
    print(f"  launch created  id={lid}  target={target.isoformat()}")

    for i, name in enumerate(STARTER_MILESTONES):
        due = today + timedelta(days=14 * (i + 1))
        body = {
            'lc_name': name,
            'lc_milestonestatus': MILESTONE_STATUS['NotStarted'],
            'lc_duedate': due.isoformat(),
            'lc_sortorder': i + 1,
            'lc_launchid@odata.bind': f"/lc_launchs({lid})",
        }
        dv.post("/api/data/v9.2/lc_milestones", body, label=f"milestone {name}")
    print(f"  milestones: {len(STARTER_MILESTONES)} starter rows queued")

    su = {
        'lc_title': f"SpinUp::Launch initialized -- {args.name}",
        'lc_body': f"Created via spin_up_launch.py. Target date: {target.isoformat()}. "
                   f"5 starter milestones seeded.",
        'lc_launchid@odata.bind': f"/lc_launchs({lid})",
    }
    dv.post("/api/data/v9.2/lc_statusupdates", su, label='spinup status update')
    print("  status updates: 1 'launch initialized' row queued")

    dv.flush_dry_log()
    print()
    if not dry:
        print(f"DONE. New launch URL: {dv.url}/main.aspx?pagetype=entityrecord"
              f"&etn=lc_launch&id={lid}")
    else:
        print("DRY RUN COMPLETE -- pass --apply to actually create the launch.")
    return 0


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