# Save as .github/workflows/uagentkit-submit.yml in a repository you maintain.
name: Suggest a project to uAgentKit

on:
  workflow_dispatch:
    inputs:
      dry_run:
        type: boolean
        default: true
        description: Validate the submission without sending it
  release:
    types: [published]

permissions:
  contents: read

jobs:
  suggest:
    if: >-
      github.event.repository.private == false &&
      (github.event_name == 'workflow_dispatch' ||
       (vars.UAGENTKIT_SUBMIT_RELEASE != '' &&
        github.event.release.tag_name == vars.UAGENTKIT_SUBMIT_RELEASE &&
        !github.event.release.prerelease))
    runs-on: ubuntu-latest
    env:
      DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
    steps:
      - name: Read maintainer-approved submission at this revision
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          gh api "repos/$GITHUB_REPOSITORY/contents/.github/uagentkit-agent.json?ref=$GITHUB_SHA" \
            --jq '.content' | base64 --decode > uagentkit-agent.json

      - name: Validate and suggest the project
        run: |
          python3 - <<'PY'
          import json
          import os
          import uuid
          from pathlib import Path
          from urllib.error import HTTPError, URLError
          from urllib.parse import urlsplit
          from urllib.request import Request, urlopen

          repo = os.environ["GITHUB_REPOSITORY"]
          draft = json.loads(Path("uagentkit-agent.json").read_text(encoding="utf-8"))
          if not isinstance(draft, dict) or set(draft) - {"name", "summary", "website", "task"}:
              raise SystemExit("Expected name, summary, optional website and optional task.")
          name, summary = draft.get("name"), draft.get("summary")
          if not isinstance(name, str) or not name.strip() or len(name) > 120:
              raise SystemExit("Set a project name of at most 120 characters.")
          if not isinstance(summary, str) or not summary.strip() or len(summary) > 3000:
              raise SystemExit("Set a factual project summary of at most 3000 characters.")
          website = draft.get("website", f"https://github.com/{repo}")
          parts = urlsplit(website) if isinstance(website, str) else None
          if not parts or len(website) > 1000 or parts.scheme != "https" or not parts.hostname or parts.username or parts.password:
              raise SystemExit("Set a public HTTPS project website without credentials.")
          agent = {"name": name.strip(), "summary": summary.strip(), "website": website,
                   "category": "Development", "relationship": "Submitted by a project maintainer."}
          if "task" in draft:
              if draft["task"] not in ("repository-agent-workflows", "browser-task-automation"):
                  raise SystemExit("Set a supported task or omit it.")
              agent["task"] = draft["task"]
          if os.environ.get("DRY_RUN") == "true":
              print("Draft checked. No submission sent.")
              raise SystemExit(0)
          request_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"https://api.github.com/repositories/{os.environ['GITHUB_REPOSITORY_ID']}#uagentkit-submission"))
          payload = json.dumps({"requestId": request_id, "agent": agent}).encode("utf-8")
          request = Request("https://uagentkit.com/api/agent-submissions", data=payload,
                            headers={"Content-Type": "application/json", "User-Agent": "uAgentKit-GitHub-Example"})
          try:
              with urlopen(request, timeout=30) as response:
                  receipt = json.load(response)
                  if response.status != 201 or receipt.get("ok") is not True or receipt.get("status") != "pending_review" or not receipt.get("receiptId"):
                      raise SystemExit("No durable receipt confirmed.")
                  print("Received for editorial review. Receipt:", receipt["receiptId"])
          except HTTPError as error:
              if error.code == 409:
                  raise SystemExit("This repository's request ID already has different content. Use the corrections page if listed, or contact uAgentKit with the receipt.")
              raise SystemExit(f"Submission returned HTTP {error.code}. Retry the same revision and content after a temporary error.")
          except (URLError, TimeoutError):
              raise SystemExit("Submission was not confirmed. Retry the same revision with the same content.")
          PY
