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

from linkedin_jobs_scraper import LinkedinScraper
from linkedin_jobs_scraper.events import Events
from linkedin_jobs_scraper.query import Query, QueryOptions


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

    cookie = payload.get("liAt") or os.environ.get("HERMES_LINKEDIN_LI_AT") or ""
    if cookie and not os.environ.get("LI_AT_COOKIE"):
        os.environ["LI_AT_COOKIE"] = cookie

    rows = []
    errors = []

    def on_data(data):
        rows.append({
            "title": getattr(data, "title", ""),
            "company": getattr(data, "company", ""),
            "company_link": getattr(data, "company_link", ""),
            "link": getattr(data, "link", ""),
            "place": getattr(data, "place", ""),
            "date": str(getattr(data, "date", "") or ""),
        })

    def on_error(error):
        errors.append(str(error))

    try:
        scraper = LinkedinScraper(
            headless=True,
            max_workers=1,
            slow_mo=float(payload.get("slowMo") or 1.0),
            page_load_timeout=int(payload.get("pageLoadTimeout") or 25),
        )
        scraper.on(Events.DATA, on_data)
        scraper.on(Events.ERROR, on_error)
        query = Query(
            query=search_term,
            options=QueryOptions(
                locations=[city or "United States"],
                limit=int(payload.get("limit") or 3),
                skip_promoted_jobs=True,
            )
        )
        scraper.run([query])
        print(json.dumps({
            "ok": True,
            "jobs": rows,
            "errors": errors,
            "text": json.dumps(rows, ensure_ascii=True),
            "emails": [],
            "phones": [],
        }, ensure_ascii=True))
    except Exception as exc:
        print(json.dumps({"ok": False, "error": str(exc), "errors": errors, "emails": [], "phones": [], "text": ""}, ensure_ascii=True))


if __name__ == "__main__":
    main()
