"""Orbe recipe — log in, then publish a post.

Runs through Orbe's internal control channel: every click and keystroke is a real
OS input event (isTrusted = true), no CDP, no debug port. Discipline is on by
default — the run stops on a verification checkpoint instead of pushing through.

Run:
    export ORBE_PROFILE=my-profile-id
    export SITE_USER=... SITE_PASS=...
    python examples/login_then_post.py "Hello from Orbe"

Credentials come from environment variables — never hard-code them in a script.
"""
import os
import sys

import orbe


def main(post_text: str) -> int:
    profile = os.environ["ORBE_PROFILE"]
    user = os.environ["SITE_USER"]
    password = os.environ["SITE_PASS"]

    # `with` opens the profile and connects the channel; it also runs Orbe's
    # pre-flight discipline checks (live proxy, active hours) before the browser opens.
    with orbe.Trinh(profile) as t:
        t.goto("https://example.com/login")
        t.wait_for("Sign in")                 # wait for the page, don't guess timing
        t.click("Username")                   # focus the field (located by visible text)
        t.type(user)
        t.click("Password")
        t.type(password, enter=True)          # submit with Enter

        # Stop safely if the platform shows a verification challenge.
        if "Verify" in t.read():
            print("Verification checkpoint — stopping, not bypassing.", file=sys.stderr)
            t.screenshot("checkpoint.png")
            return 2

        t.goto("https://example.com/compose")
        t.wait_for("What's on your mind")
        t.click("What's on your mind")
        t.type(post_text)
        t.click("Post")
        t.wait_for("Your post was published")
        print("Posted.")
    return 0


if __name__ == "__main__":
    text = sys.argv[1] if len(sys.argv) > 1 else "Hello from Orbe"
    try:
        raise SystemExit(main(text))
    except orbe.Blocked as e:
        # Any discipline block (checkpoint, rate limit, off-hours, proxy…) lands here.
        print(f"Blocked: {e}", file=sys.stderr)
        raise SystemExit(2)
