#!/usr/bin/env python3
"""Ask → wait → download session artifact (CI-friendly, no webhook token)."""

from __future__ import annotations

import argparse
import os
import sys

from stackgen import StackgenClient, StackgenConfig


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Start Ask, poll execution, download a session artifact.",
    )
    parser.add_argument("--base-url", default=os.environ.get("STACKGEN_URL", ""), help="Mothership URL (no /guild suffix)")
    parser.add_argument("--api-token", default=os.environ.get("STACKGEN_TOKEN", ""), help="API token (stackgen_…)")
    parser.add_argument(
        "--workspace-id",
        "--org-id",
        default=os.environ.get("STACKGEN_WORKSPACE_ID") or os.environ.get("STACKGEN_PROJECT") or os.environ.get("STACKGEN_PROJECT_ID", ""),
        help="Workspace UUID (sent as orgId)",
    )
    parser.add_argument("--message", required=True, help="Natural-language task for Ask")
    parser.add_argument(
        "--workflow-name",
        required=True,
        help="Workflow skill name to pin via entity_refs",
    )
    parser.add_argument("--timeout-seconds", type=int, default=1800)
    parser.add_argument(
        "--artifact-name",
        default="session-report.md",
        help="Session artifact filename to download",
    )
    parser.add_argument(
        "--output-path",
        default="session-report.md",
        help="Local path to write the artifact",
    )
    args = parser.parse_args()
    if not args.base_url or not args.api_token or not args.workspace_id:
        parser.error("set --base-url/--api-token/--workspace-id or STACKGEN_URL/STACKGEN_TOKEN/STACKGEN_WORKSPACE_ID")

    client = StackgenClient(
        StackgenConfig(
            base_url=args.base_url,
            api_token=args.api_token,
            workspace_id=args.workspace_id,
            artifact_name=args.artifact_name,
            output_path=args.output_path,
            timeout_seconds=args.timeout_seconds,
        )
    )
    result = client.aiden.run_ask_and_download_artifact(
        args.message,
        entity_refs=[{"name": args.workflow_name, "type": "workflow"}],
        artifact_name=args.artifact_name,
        output_path=args.output_path,
    )
    print(
        f"trace_id={result.trace_id} session_id={result.session_id} "
        f"output={result.output_path}",
        file=sys.stderr,
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
