#!/usr/bin/env python3
"""Copy for CRM: turn one Diary conversation into clean, paste-ready plain text for a CRM note field.

RecapMuse build spec 03 (phase 1). Matches the live marketing copy exactly ("...to paste into your
CRM," a copy-formatted export, NOT an automatic API sync). Given a conversation (found in diary.json by
its key = the first clip's filename, the same key citations.py uses), it emits a one-line summary, key
topics, and bulleted next steps. If the Recall edition has added talk-ratio / objections to the
conversation, those are included too. Plain text only: no markdown syntax a CRM would mangle.

Pure stdlib (system /usr/bin/python3). The Swift shell copies the returned `text` to the clipboard.

  crm_export.py --rec-dir DIR --conv-key "2026-06-16_09-08-54.aac"   # JSON: {ok, text, title}
  crm_export.py DIR "2026-06-16_09-08-54.aac"                         # positional form (testing)
"""
import json
import os
import sys


def _find_conv(diary, key):
    """Return (conversation, day) for the conversation whose first clip file == key."""
    for day in diary.get("days", []):
        for cv in day.get("conversations", []):
            clips = cv.get("clips") or []
            if clips and clips[0].get("file") == key:
                return cv, day
    return None, None


def _clean(s):
    return " ".join(str(s or "").split())


def format_crm(cv, day):
    """Build the paste-ready CRM note. Deterministic, offline, no model call."""
    lines = []
    title = _clean(cv.get("title")) or "Conversation"
    lines.append(title)

    # Context line: who + when.
    ctx = []
    who = _clean(cv.get("who_with"))
    if who and who.lower() not in ("", "unclear", "no one / working solo"):
        ctx.append(who)
    when = _clean(cv.get("time_range"))
    heading = _clean(day.get("heading")) if day else ""
    if heading:
        ctx.append(heading + (" " + when if when else ""))
    elif when:
        ctx.append(when)
    if ctx:
        lines.append(" · ".join(ctx))

    # One-line summary.
    summary = _clean(cv.get("summary"))
    if summary:
        lines.append("")
        lines.append("Summary")
        lines.append(summary)

    # Talk ratio (Recall edition): expressed as you / them percentages.
    tr = cv.get("talk_ratio")
    if isinstance(tr, (int, float)):
        you = int(round(max(0.0, min(1.0, tr)) * 100))
        lines.append("")
        lines.append("Talk ratio: you %d%% / them %d%%" % (you, 100 - you))

    # Key topics.
    topics = [t for t in (cv.get("topics") or []) if _clean(t)]
    if topics:
        lines.append("")
        lines.append("Key topics: " + ", ".join(_clean(t) for t in topics))

    # Objections (Recall edition).
    objections = [o for o in (cv.get("objections") or []) if _clean(o)]
    if objections:
        lines.append("")
        lines.append("Objections raised")
        for o in objections:
            lines.append("- " + _clean(o))

    # Next steps (from action items).
    steps = [a for a in (cv.get("action_items") or []) if _clean(a)]
    lines.append("")
    lines.append("Next steps")
    if steps:
        for a in steps:
            lines.append("- " + _clean(a))
    else:
        lines.append("- (none captured)")

    return "\n".join(lines).strip() + "\n"


def run(rec_dir, key):
    diary_path = os.path.join(os.path.expanduser(rec_dir), "diary.json")
    if not os.path.exists(diary_path):
        return {"ok": False, "error": "no diary yet (organize your recordings first)"}
    try:
        diary = json.load(open(diary_path))
    except Exception as e:  # noqa: BLE001
        return {"ok": False, "error": "could not read diary.json: %s" % (str(e)[:120])}
    cv, day = _find_conv(diary, key)
    if not cv:
        return {"ok": False, "error": "conversation not found: %s" % key}
    text = format_crm(cv, day)
    return {"ok": True, "text": text, "title": _clean(cv.get("title"))}


def main(argv):
    rec_dir, key = "", ""
    if "--rec-dir" in argv:
        rec_dir = argv[argv.index("--rec-dir") + 1]
    if "--conv-key" in argv:
        key = argv[argv.index("--conv-key") + 1]
    if not rec_dir or not key:                      # positional fallback (testing)
        pos = [a for a in argv if not a.startswith("--")]
        if len(pos) >= 2:
            rec_dir, key = pos[0], pos[1]
    if not rec_dir or not key:
        sys.stdout.write(json.dumps({"ok": False, "error": "usage: --rec-dir DIR --conv-key KEY"}))
        return
    sys.stdout.write(json.dumps(run(rec_dir, key)))


if __name__ == "__main__":
    main(sys.argv[1:])
