#!/usr/bin/env python3
"""Drive the existing staged API; no additional backend pipeline or wallet.

python dramamaster_client.py script.txt --run-id your-stable-run-id
Set DRAMAMASTER_API_KEY in the environment. API calls incur normal point charges.
POSTs are never retried automatically after a transport failure. Restart with the
same run ID to retrieve accepted submissions through server-side idempotency.
"""
from __future__ import annotations
import argparse
import json
import os
import time
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError


class DramaMasterRequestError(RuntimeError):
    def __init__(self, status, payload, *, headers=None, idempotency_key=None):
        data = payload.get("data") if isinstance(payload, dict) else None
        data = data if isinstance(data, dict) else {}
        self.status = status
        self.error_code = data.get("error_code")
        self.request_id = data.get("request_id") or (headers.get("X-Request-Id") if headers else None)
        self.task_accepted = data.get("task_accepted")
        self.retry_after = headers.get("Retry-After") if headers else None
        self.idempotency_key = idempotency_key
        suffix = f" ({self.error_code})" if self.error_code else ""
        trace = f", request {self.request_id}" if self.request_id else ""
        super().__init__(f"DramaMaster HTTP {status}{suffix}{trace}")


class PartialAcceptanceError(RuntimeError):
    def __init__(self, drama_id, stage, task_ids, idempotency_key):
        self.drama_id = drama_id
        self.stage = stage
        self.task_ids = task_ids
        self.idempotency_key = idempotency_key
        super().__init__(
            f"Episode {drama_id}: {stage} only partially accepted. "
            f"Check tasks {', '.join(task_ids)} before submitting remaining work."
        )


def accepted_task_ids(accepted):
    ids = [task["task_id"] for task in (accepted.get("tasks") or [])]
    ids.extend(accepted.get("task_ids") or [])
    if accepted.get("task_id"):
        ids.append(accepted["task_id"])
    return list(dict.fromkeys(ids))


class DramaMasterClient:
    def __init__(self, key: str, *, base_url: str = "https://dramamaster.ai", locale: str = "en-US", poll_seconds: float = 10):
        if not key.startswith(("dm_live_", "dm_test_", "sk_live_", "sk_test_")):
            raise ValueError("A DramaMaster API key is required")
        self.key, self.base_url, self.locale = key, base_url.rstrip('/'), locale
        self.poll_seconds = max(10, poll_seconds)
        self._last_request_at = None

    def call(self, path: str, *, body: dict | None = None, idempotency_key: str | None = None, deadline: float | None = None, method: str | None = None) -> dict:
        headers = {"Authorization": f"Bearer {self.key}", "Accept-Language": self.locale, "Content-Type":"application/json", "User-Agent": "DramaMaster-SDK/1.0"}
        if idempotency_key: headers["Idempotency-Key"] = idempotency_key
        request = Request(self.base_url+'/api/developer/v1'+path, data=json.dumps(body).encode() if body is not None else None,
            headers=headers, method=method or ("POST" if body is not None else "GET"))
        deadline = deadline if deadline is not None else time.monotonic() + 240
        retries = 0
        while True:
            now = time.monotonic()
            delay = max(0, 7 - (now - self._last_request_at)) if self._last_request_at is not None else 0
            if now + delay >= deadline:
                raise TimeoutError("Request wait timed out; resume with the same run ID")
            if delay: time.sleep(delay)
            self._last_request_at = time.monotonic()
            try:
                with urlopen(request, timeout=min(60, max(0.1, deadline - time.monotonic()))) as response:
                    payload=json.load(response)
                    status = getattr(response, "status", 200)
                break
            except HTTPError as exc:
                # Only retry GETs after an explicit rate-limit response. A POST
                # with an uncertain outcome must be reconciled using its run ID.
                if request.method != 'GET' or exc.code != 429 or retries >= 3:
                    try:
                        payload = json.load(exc) if exc.fp is not None else {}
                    except (ValueError, OSError):
                        payload = {}
                    finally:
                        exc.close()
                    raise DramaMasterRequestError(
                        exc.code, payload, headers=exc.headers, idempotency_key=idempotency_key
                    ) from None
                try: delay = max(7, float(exc.headers.get('Retry-After', '60')))
                except (TypeError, ValueError): delay = 60
                finally: exc.close()
                if time.monotonic() + delay >= deadline:
                    raise TimeoutError("Rate-limit wait timed out; resume with the same run ID") from None
                time.sleep(delay)
                retries += 1
        if payload.get('code') != 200:
            raise DramaMasterRequestError(status, payload, idempotency_key=idempotency_key)
        return payload['data']

    def wait_tasks(self, ids: list[str], *, deadline: float) -> list[dict]:
        pending=set(ids)
        results={}
        while pending:
            if time.monotonic() >= deadline: raise TimeoutError("Task wait timed out; resume with the same run ID")
            for task_id in list(pending):
                task=self.call('/tasks/'+task_id, deadline=deadline)
                if task['status']=='failed':
                    raise RuntimeError(f"Task {task_id} failed; inspect it before resubmitting")
                if task['status']=='completed':
                    pending.remove(task_id);results[task_id]=task
                elif task.get('execution_state')=='submit_unknown':
                    raise RuntimeError(f"Task {task_id} requires reconciliation; do not resubmit generation")
            if pending: time.sleep(self.poll_seconds)
        return [results[task_id] for task_id in ids]

    def start_from_idea(self, idea: str, *, idempotency_key: str,
                        duration_seconds: int = 15, aspect_ratio: str = '9:16',
                        style: str = 'realistic', reference_image_urls: list[str] | None = None) -> dict:
        """Start a single episode and its background run using the original workflow."""
        if not idempotency_key.strip():
            raise ValueError("Use a stable Idempotency-Key for the idea")
        return self.call('/dramas/ideas', body={
            'idea': idea,
            'duration_seconds': duration_seconds,
            'aspect_ratio': aspect_ratio,
            'style': style,
            **({'reference_image_urls': reference_image_urls} if reference_image_urls else {}),
        }, idempotency_key=idempotency_key)

    def get_drama(self, drama_id: int) -> dict:
        """Read the episode, review inputs, task statuses and current result URL."""
        return self.call(f'/dramas/{drama_id}')

    def review_sample(self, drama_id: int, *, expected_revision: int, shot_id: int,
                      signature: str, skip: bool = False) -> dict:
        """Record a decision for the current first clip without starting work."""
        return self.call(f'/dramas/{drama_id}/review', method='PATCH', body={
            'expected_revision': expected_revision,
            'shot_id': shot_id,
            'signature': signature,
            'status': 'skipped' if skip else 'approved',
        })

    def background_run(self, drama_id: int) -> dict | None:
        """Read the durable coordinator; closing this client does not stop it."""
        return self.call(f'/dramas/{drama_id}/run')

    def start_background_run(self, drama_id: int, *, resume: bool = False) -> dict:
        """Start/resume the existing coordinator, without a user spending cap."""
        return self.call(f'/dramas/{drama_id}/run',body={'action':'resume' if resume else 'start'})

    def approve_background_run(self, drama_id: int, *, resume: bool = False, **_legacy_options) -> dict:
        """Compatibility alias; retired user-cap arguments have no effect."""
        return self.start_background_run(drama_id, resume=resume)

    def stop_background_run(self, drama_id: int) -> dict | None:
        """Stop future admissions; already accepted tasks retain their lifecycle."""
        return self.call(f'/dramas/{drama_id}/run',body={'action':'stop'})

    def create_and_export(self, script: str, *, run_id: str, timeout_seconds: float = 7200) -> dict:
        if not run_id.strip(): raise ValueError("Use a stable, non-empty run ID for safe resumption")
        deadline=time.monotonic()+timeout_seconds
        create_key = run_id + ':create'
        accepted = self.call('/dramas', body={'script': script}, idempotency_key=create_key, deadline=deadline)
        drama_id = accepted.get('drama_id')
        if accepted.get('partial'):
            raise PartialAcceptanceError(drama_id, 'storyboard', accepted_task_ids(accepted), create_key)
        self.wait_tasks([accepted['task_id']], deadline=deadline)
        batches={stage:0 for stage in ('assets','images','videos','export')}
        while time.monotonic()<deadline:
            episode=self.call(f'/dramas/{drama_id}',deadline=deadline)
            stage=episode['next_stage']
            if stage=='completed':return {'drama_id':drama_id,'result_url':episode['result_url']}
            if stage not in batches:raise RuntimeError(f"Episode {drama_id} is not ready for media submission")
            batch_key = f'{run_id}:{stage}:{batches[stage]}'
            accepted = self.call(f'/dramas/{drama_id}/{stage}', body={}, idempotency_key=batch_key, deadline=deadline)
            ids = accepted_task_ids(accepted)
            if accepted.get('partial'):
                raise PartialAcceptanceError(drama_id, stage, ids, batch_key)
            if not ids:raise RuntimeError(f"Episode {drama_id} did not accept any {stage} tasks; inspect prerequisites")
            completed=self.wait_tasks(ids,deadline=deadline)
            if stage=='export':
                result=next((t['result_url'] for t in completed if t.get('result_url')),None)
                if not result:raise RuntimeError("Export completed without a result URL")
                return {'drama_id':drama_id,'result_url':result}
            batches[stage]+=1
        raise TimeoutError("Pipeline wait timed out; resume with the same run ID")


if __name__=='__main__':
    parser=argparse.ArgumentParser(description="Submit a script and drive the existing short-drama API")
    parser.add_argument('script',type=Path)
    parser.add_argument('--run-id',required=True)
    parser.add_argument('--base-url',default='https://dramamaster.ai')
    parser.add_argument('--locale',default='en-US')
    args=parser.parse_args()
    client=DramaMasterClient(os.environ.get('DRAMAMASTER_API_KEY',''),base_url=args.base_url,locale=args.locale)
    result=client.create_and_export(args.script.read_text(),run_id=args.run_id)
    # Signed result URLs are private capabilities; save them to a private file.
    output=Path('drama-result.json')
    output.touch(mode=0o600,exist_ok=True);output.chmod(0o600)
    output.write_text(json.dumps(result,indent=2)+'\n')
    print(f"Episode {result['drama_id']} completed; result saved to {output}")
