#!/usr/bin/env python3
"""MoneyTools Transcripts: pay-per-file speech-to-text over x402 (no prepaid credits).

dTelecom-compatible API (POST /v1/transcriptions/jobs), paid per file in USDC on Base:
0.005 USDC per started audio minute, no minimum, up to 180 min / 100 MB per file.

  pip install "x402[requests,evm]" eth-account
  export X402_PRIVATE_KEY=0x...   # Base wallet holding a little USDC (no ETH/gas needed)
  python transcribe.py meeting.mp3              # local file (multipart upload)
  python transcribe.py https://host/ep.mp3      # direct media URL (we fetch it)
  MAX_USD=0.10 FORMAT=srt python transcribe.py meeting.mp3 > meeting.srt

Flow: POST -> HTTP 402 with the exact price for THIS file -> the x402 client signs a
USDC authorization and resends the same request (same Idempotency-Key, so the stored
upload is reused) -> 202 {id, job_token} -> poll GET /v1/transcriptions/jobs/{id}.
The first ~5-minute segment is transcribed before the payment settles, so unreadable
files are never charged.
"""
import os, sys, time, uuid
import requests
from eth_account import Account
from x402 import x402ClientSync, max_amount
from x402.http.clients import x402_requests
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact import ExactEvmScheme

BASE = os.environ.get("TRANSCRIPTS_BASE", "https://speech.moneytools.dev").rstrip("/")
MAX_USD = float(os.environ.get("MAX_USD", "0.50"))  # refuse to pay more than this per file
FORMAT = os.environ.get("FORMAT", "json")           # json | srt | vtt | txt


def paying_session():
    key = os.environ.get("X402_PRIVATE_KEY")
    if not key:
        sys.exit("set X402_PRIVATE_KEY (a Base wallet with USDC)")
    client = x402ClientSync()
    client.register("eip155:8453", ExactEvmScheme(signer=EthAccountSigner(Account.from_key(key))))
    client.register_policy(max_amount(int(MAX_USD * 1_000_000)))  # USDC has 6 decimals
    return x402_requests(client)


def submit(session, src):
    url = f"{BASE}/v1/transcriptions/jobs"
    if src.startswith("https://"):
        # JSON body: no upload; the x402 client simply resends it with PAYMENT-SIGNATURE.
        return session.post(url, json={"url": src}, timeout=300)
    # Multipart, exactly like dTelecom: file + optional language/diarize.
    # Same Idempotency-Key on the paid retry => the server reuses the stored upload.
    with open(src, "rb") as f:
        data = f.read()
    headers = {"Idempotency-Key": f"py-{uuid.uuid4().hex}"}
    files = {"file": (os.path.basename(src), data, "application/octet-stream")}
    return session.post(url, files=files, data={}, headers=headers, timeout=600)


def main():
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    s = paying_session()
    try:
        r = submit(s, sys.argv[1])
    except Exception as e:  # e.g. price above MAX_USD (policy filtered every offer)
        sys.exit(f"payment not created: {e} (MAX_USD={MAX_USD}; free quote: {BASE}/v1/speech/quote?minutes=60)")
    if r.status_code == 402:
        body = r.json()
        sys.exit(f"not paid: {body.get('error')} (price {(body.get('quote') or {}).get('amountUsd')} USDC, MAX_USD={MAX_USD})")
    if r.status_code != 202:
        sys.exit(f"HTTP {r.status_code}: {r.text[:500]}")
    job = r.json()
    print(f"paid {job['payment']['amountUsd']} USDC, tx {job['payment'].get('transaction')}; job {job['id']}", file=sys.stderr)
    auth = {"Authorization": f"Bearer {job['job_token']}"}  # shown once: keep it
    status_url = job["status_url"]
    while True:
        st = requests.get(status_url, headers=auth, timeout=60).json()
        print(f"  {st['status']} {st.get('moneytools', {}).get('progress')}", file=sys.stderr)
        if st["status"] in ("completed", "failed"):
            break
        time.sleep(job.get("poll_every_seconds", 15))
    if st["status"] == "failed":
        sys.exit(f"job failed: {st.get('error')}")
    if FORMAT == "json":
        print(st["result"]["text"])
    else:
        print(requests.get(f"{status_url}?format={FORMAT}", headers=auth, timeout=60).text)


if __name__ == "__main__":
    main()
