#!/usr/bin/env python3
"""rap_metadata.py — write YOUTUBE-UPLOAD.md, the one-file upload pack.

Same artifact name rhyme-factory writes, so an operator learns ONE convention — but
composed from this lane's pack vars rather than the rhyme set (whose Devanagari title
pair, nursery kicker and hardcoded chapter times do not apply here).

Everything comes from the pack (set -a sourced, so plain env here): BOOKEND_TITLE,
DISPLAY_NAME, KICKER, YT_BLURB, YT_TAGS, YT_HASHTAGS, YT_CATEGORY, MADE_FOR_KIDS,
YT_PRIVACY — plus the lyric sheet for the description body.

Usage:
  rap_metadata.py --project <dir> --slug <slug> [--out <path>]

Exit 0 written · 2 bad input.
"""
from __future__ import annotations

import argparse
import os
import sys


def env(name: str, default: str = "") -> str:
    return os.environ.get(name, default).strip()


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--slug", required=True)
    ap.add_argument("--out", default="")
    args = ap.parse_args()

    P = args.project
    out = args.out or os.path.join(P, "YOUTUBE-UPLOAD.md")

    title = env("BOOKEND_TITLE") or env("DISPLAY_NAME") or args.slug
    display = env("DISPLAY_NAME") or title
    kicker = env("KICKER")
    blurb = env("YT_BLURB")
    tags = env("YT_TAGS")
    hashtags = env("YT_HASHTAGS")
    category = env("YT_CATEGORY", "Music")
    made_for_kids = env("MADE_FOR_KIDS", "no").lower() in ("1", "true", "yes")
    privacy = env("YT_PRIVACY", "unlisted")

    lyrics = ""
    lyr_path = os.path.join(P, "references", "lyrics.txt")
    if os.path.isfile(lyr_path):
        lyrics = "\n".join(
            l.rstrip() for l in open(lyr_path, encoding="utf-8")
            if not l.strip().startswith("["))

    candidates = [t for t in dict.fromkeys([
        title,
        f"{title} (Official Music Video)" if title else "",
        f"{display} — {kicker}" if kicker and kicker.lower() not in title.lower() else "",
    ]) if t]

    doc = f"""# YouTube upload — {args.slug}

**Video:** `final/videos/film/` — the `-YT.mp4` master (loudness-normalised, verified)
**Thumbnail:** `final/thumbnail.png`
**Privacy on upload:** {privacy}

## Title (pick one)

""" + "\n".join(f"{i + 1}. {t}" for i, t in enumerate(candidates)) + f"""

## Description

{blurb or f'{title} — a one-of-a-kind rap music video.'}

LYRICS

{lyrics.strip() or '(references/lyrics.txt was empty)'}

{hashtags}

## Tags

{tags or '(set YT_TAGS in the pack)'}

## Upload settings

- Audience: {"Yes, made for kids" if made_for_kids else "No, not made for kids"}
- Category: {category}
- Language: English
- Altered content (AI): Yes — synthetic/altered visuals
"""
    with open(out, "w", encoding="utf-8") as fh:
        fh.write(doc)
    print(f"rap_metadata: {len(candidates)} title candidate(s), "
          f"{'kids' if made_for_kids else 'not-kids'}, {category} -> {out}")

    missing = [n for n in ("YT_TAGS", "YT_BLURB") if not env(n)]
    if missing:
        print(f"  note: {', '.join(missing)} unset in the pack — the sheet carries "
              f"placeholders where they belong", file=sys.stderr)


if __name__ == "__main__":
    main()
