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

from linkedin_scraper.core.auth import login_with_cookie
from linkedin_scraper.core.browser import BrowserManager
from linkedin_scraper.scrapers.person import PersonScraper


def main():
    try:
        payload = json.loads(sys.stdin.read() or "{}")
    except Exception:
        payload = {}
    result = asyncio.run(scrape(payload))
    print(json.dumps(result, ensure_ascii=True))


async def scrape(payload):
    url = payload.get("url") or ""
    if not url:
        return failed("missing LinkedIn profile URL")

    session_path = payload.get("sessionPath") or os.environ.get("HERMES_LINKEDIN_SESSION_JSON") or ""
    cookie = payload.get("liAt") or os.environ.get("HERMES_LINKEDIN_LI_AT") or ""
    if not session_path and not cookie:
        return {"ok": False, "skipped": True, "error": "missing HERMES_LINKEDIN_SESSION_JSON or HERMES_LINKEDIN_LI_AT"}

    try:
        async with BrowserManager(headless=True) as browser:
            if session_path:
                await browser.load_session(session_path)
            elif cookie:
                await login_with_cookie(browser.page, cookie)

            scraper = PersonScraper(browser.page)
            person = await scraper.scrape(url)
            data = model_data(person)
            text = json.dumps(data, ensure_ascii=True)
            return {
                "ok": True,
                "profile": data,
                "emails": extract_emails(text),
                "phones": extract_phones(text),
                "text": text,
            }
    except Exception as exc:
        return failed(str(exc))


def model_data(value):
    if hasattr(value, "model_dump"):
        return value.model_dump(mode="json")
    if hasattr(value, "dict"):
        return value.dict()
    if isinstance(value, list):
        return [model_data(item) for item in value]
    if isinstance(value, dict):
        return {key: model_data(item) for key, item in value.items()}
    return value


def extract_emails(text):
    return sorted(set(re.findall(r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", text or "", re.I)))


def extract_phones(text):
    return sorted(set(re.findall(r"(?:\+?1[\s.-]?)?(?:\(?\d{3}\)?[\s.-]?)\d{3}[\s.-]?\d{4}", text or "")))


def failed(message):
    return {"ok": False, "error": message or "linkedin_scraper bridge failed", "emails": [], "phones": [], "text": ""}


if __name__ == "__main__":
    main()
