#!/usr/bin/env python3
"""Minimal MoltJobs agent: discover, heartbeat, print live API output."""
from __future__ import annotations

import json
import os
import urllib.error
import urllib.request

API = "https://api.moltjobs.io/v1"
KEY = os.environ.get("MOLTJOBS_API_KEY", "")
AID = os.environ.get("MOLTJOBS_AGENT_ID", "alexandeross-mm")


def call(method: str, path: str, payload: dict | None = None, auth: bool = True) -> tuple[int, object]:
    headers = {"User-Agent": "alexandeross-mm-minimal-agent/1.0", "Accept": "application/json"}
    if auth:
        if not KEY:
            raise SystemExit("MOLTJOBS_API_KEY is not set")
        headers["Authorization"] = "Bearer " + KEY
    data = None
    if payload is not None:
        data = json.dumps(payload).encode()
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(API + path, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=25) as resp:
            raw = resp.read()
            try:
                body = json.loads(raw)
            except json.JSONDecodeError:
                body = raw.decode("utf-8", "replace")[:400]
            return resp.status, body
    except urllib.error.HTTPError as e:
        raw = e.read()
        try:
            body = json.loads(raw)
        except Exception:
            body = raw.decode("utf-8", "replace")[:400]
        return e.code, body


def redact(obj):
    if isinstance(obj, dict):
        out = {}
        for k, v in obj.items():
            if any(s in k.lower() for s in ("key", "token", "secret", "authorization")):
                out[k] = "[REDACTED]"
            else:
                out[k] = redact(v)
        return out
    if isinstance(obj, list):
        return [redact(x) for x in obj]
    return obj


def main() -> None:
    print("=== GET /jobs?status=OPEN (public) ===")
    s, d = call("GET", "/jobs?status=OPEN&limit=50", auth=False)
    print("HTTP", s)
    jobs = (d.get("data") if isinstance(d, dict) else []) or []
    print("open_count_this_page", len(jobs))
    funded = []
    for j in jobs:
        try:
            b = float(j.get("budgetUsdc") or 0)
        except Exception:
            b = 0
        row = (
            b,
            j.get("status"),
            bool(j.get("escrowTxHash")),
            (j.get("title") or "")[:70],
        )
        if b >= 1:
            funded.append(row)
            print("-", *row, "tx", (j.get("escrowTxHash") or "")[:18])
    print("jobs_budget_gte_1.5", len(funded))
    print("first_five_any", [(j.get("budgetUsdc"), (j.get("title") or "")[:50]) for j in jobs[:5]])

    print("\n=== POST /agents/heartbeat ===")
    s, d = call("POST", "/agents/heartbeat", {"statusReport": "minimal agent poll"})
    print("HTTP", s)
    if isinstance(d, dict) and isinstance(d.get("data"), dict):
        print("agent_status", d["data"].get("status"), "id", d["data"].get("id"))

    print("\n=== GET /agents/{id} ===")
    s, d = call("GET", "/agents/" + AID)
    print("HTTP", s)
    if isinstance(d, dict) and isinstance(d.get("data"), dict):
        a = d["data"]
        print(
            "status",
            a.get("status"),
            "vertical",
            a.get("vertical"),
            "rep",
            a.get("reputationScore"),
            "passedFundamentals",
            a.get("passedFundamentals"),
        )

    print("\n=== GET /stats (public) ===")
    s, d = call("GET", "/stats", auth=False)
    print("HTTP", s)
    print(json.dumps(redact(d), indent=2)[:800])


if __name__ == "__main__":
    main()
