#!/usr/bin/env python3
"""
Pericle Companion v1.0
─────────────────────────────────────────────────────
Installa dipendenze (una volta sola):
  pip install "python-socketio[asyncio_client]" playwright
  playwright install chromium

Poi avvia:
  python companion.py
─────────────────────────────────────────────────────
"""
import asyncio
import sys
from pathlib import Path
from playwright.async_api import async_playwright
import socketio

SERVER      = "https://pericle.providencestudioweb.online"
SESSION_UID = "c714ec2e-b6f4-4bb4-9608-6deba01e8d19"

LI_AT = ""

sio = socketio.AsyncClient(logger=False, engineio_logger=False)


async def scrape(url: str) -> str:
    profile_dir = Path.home() / ".pericle" / "chromium"
    profile_dir.mkdir(parents=True, exist_ok=True)

    async with async_playwright() as p:
        ctx = await p.chromium.launch_persistent_context(
            user_data_dir=str(profile_dir),
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-blink-features=AutomationControlled",
                "--disable-dev-shm-usage",
            ],
        )
        if LI_AT:
            await ctx.add_cookies([{
                "name": "li_at", "value": LI_AT,
                "domain": ".linkedin.com", "path": "/",
                "secure": True, "httpOnly": True, "sameSite": "None",
            }])
        page = ctx.pages[0] if ctx.pages else await ctx.new_page()
        try:
            await page.goto(url, wait_until="domcontentloaded", timeout=30000)
            await asyncio.sleep(2)
            return await page.inner_text("body")
        except Exception as e:
            return f"ERROR:{e}"
        finally:
            await ctx.close()


@sio.event
async def connect():
    print(f"\n✓ Connesso a {SERVER}")
    await sio.emit("companion_connect", {"uid": SESSION_UID})


@sio.event
async def disconnect():
    print("✗ Disconnesso dal server")


@sio.on("companion_auth")
async def on_auth(data):
    global LI_AT
    LI_AT = data.get("li_at", "")
    if LI_AT:
        print("  ✓ Cookie LinkedIn ricevuto")
    else:
        print("  ⚠ Nessun cookie — fai prima il login su Pericle")
    print("  In attesa di richieste... (Ctrl+C per uscire)\n")


@sio.on("scrape_request")
async def on_request(data):
    url = data.get("url", "")
    print(f"  → {url}")
    text = await scrape(url)
    ok = not text.startswith("ERROR")
    print(f"  {'✓' if ok else '✗'} {len(text) if ok else text[:80]}")
    await sio.emit("companion_result", {"uid": SESSION_UID, "url": url, "text": text})


async def main():
    bar = "─" * 50
    print(bar)
    print("  Pericle Companion")
    print(f"  Server : {SERVER}")
    print(f"  UID    : {SESSION_UID[:16]}...")
    print(bar)
    print(f"\nConnessione...")
    try:
        await sio.connect(SERVER)
        await sio.wait()
    except KeyboardInterrupt:
        print("\n  Uscita.")
    except Exception as e:
        print(f"\n✗ Errore: {e}")
        print("  Verifica connessione internet e riprova.")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
