import os
import sys
import time
from stacklink import Stacklink

stacklink = Stacklink(
    api_key=os.environ["STACKLINK_API_KEY"],
    base_url=os.environ.get("STACKLINK_API_URL", "https://api.stacklink.in"),
)
definition = {
    "nodes": [
        {"id": "start", "name": "Ticket received", "type": "start", "config": {},
         "position": {"x": 0, "y": 0}},
        {"id": "result", "name": "Return ticket ID", "type": "return",
         "config": {"value": {"kind": "input", "path": ["ticketId"]}},
         "position": {"x": 340, "y": 0}},
    ],
    "edges": [{"id": "start-result", "source": "start", "target": "result"}],
    "inputSchema": {"type": "object", "properties": {"ticketId": {"type": "string"}},
                    "required": ["ticketId"]},
}


def observe(workflow_id, run_id):
    for _ in range(30):
        run = stacklink.workflows.get_run(workflow_id, run_id)
        if run["status"] not in ("queued", "running", "retrying"):
            return run
        time.sleep(1)
    return stacklink.workflows.get_run(workflow_id, run_id)


checked = stacklink.workflows.validate(definition)
if not checked["valid"]:
    raise RuntimeError(checked["issues"])
workflow_id = os.environ.get("STACKLINK_WORKFLOW_ID")
workflow = (stacklink.workflows.get(workflow_id) if workflow_id else
            stacklink.workflows.create("Docs · Ticket intake", definition, source="visual"))
# Demo identities. Derive these from your authenticated user in a real app.
session = stacklink.sessions.create_bound({
    "externalTenantId": "demo-company", "externalUserId": "demo-user",
})
print({"workflowId": workflow["id"], "sessionId": session.id})
test = stacklink.workflows.run(
    workflow["id"], session.id, f"docs-test-{workflow['revision']}",
    revision=workflow["revision"], purpose="test", mode="simulation",
    input={"ticketId": "ticket-42"},
)
tested = observe(workflow["id"], test["id"])
print({"testRunId": test["id"], "status": tested["status"], "output": tested["output"]})
if tested["status"] != "completed":
    raise RuntimeError("Test has not completed. Inspect its saved run before publishing.")
if "--publish" in sys.argv:
    stacklink.workflows.publish(workflow["id"], workflow["revision"])
    run = stacklink.workflows.run(
        workflow["id"], session.id, "docs-ticket-42", purpose="operational",
        input={"ticketId": "ticket-42"},
    )
    result = observe(workflow["id"], run["id"])
    print({"runId": run["id"], "status": result["status"], "output": result["output"]})
else:
    print("Draft kept. Review it in Workflows before running with --publish.")
# Waiting or still running is not failure. Keep the IDs and inspect later.
