#!/usr/bin/env python3
import json
import sys

from jobspy import scrape_jobs


def main():
    try:
        payload = json.loads(sys.stdin.read() or "{}")
    except Exception:
        payload = {}

    business = payload.get("businessName") or ""
    owner = payload.get("ownerName") or ""
    city = payload.get("city") or ""
    search_term = business or owner
    if not search_term:
        print(json.dumps({"ok": False, "skipped": True, "error": "missing businessName or ownerName"}))
        return

    try:
        jobs = scrape_jobs(
            site_name="linkedin",
            search_term=search_term,
            location=city or "United States",
            results_wanted=int(payload.get("limit") or 5),
            linkedin_fetch_description=False,
            verbose=0,
        )
        rows = json.loads(jobs.head(int(payload.get("limit") or 5)).to_json(orient="records"))
        print(json.dumps({
            "ok": True,
            "jobs": rows,
            "text": json.dumps(rows, ensure_ascii=True),
            "emails": [],
            "phones": [],
        }, ensure_ascii=True))
    except Exception as exc:
        print(json.dumps({"ok": False, "error": str(exc), "emails": [], "phones": [], "text": ""}, ensure_ascii=True))


if __name__ == "__main__":
    main()
