#!/usr/bin/env python3
"""Persistent, isolated profiles for authorized social accounts; no stealth or proxy rotation."""
import argparse, os, re, sqlite3, sys, time
from datetime import datetime, timezone
from pathlib import Path
from playwright.sync_api import sync_playwright

BASE = Path("/root/.gemini/antigravity/scratch/social-matrix")
PROFILE_ROOT = BASE / "managed_profiles"
STATE_ROOT = BASE / "managed_state"
DB = STATE_ROOT / "sessions.sqlite3"
PLATFORMS = {"facebook": "https://www.facebook.com/", "instagram": "https://www.instagram.com/"}
ROOT_RE = re.compile(r"^[A-Z0-9][A-Z0-9_-]{1,31}$")

def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")

def valid_root(value):
    value = value.strip().upper()
    if not ROOT_RE.fullmatch(value):
        raise SystemExit("Invalid root code (2-32 letters, numbers, _ or -).")
    return value

def ensure():
    os.umask(0o077)
    PROFILE_ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    STATE_ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    os.chmod(PROFILE_ROOT, 0o700)
    os.chmod(STATE_ROOT, 0o700)
    with sqlite3.connect(DB) as c:
        c.execute("""CREATE TABLE IF NOT EXISTS sessions(
            root_code TEXT NOT NULL, platform TEXT NOT NULL, profile_path TEXT NOT NULL,
            created_at TEXT NOT NULL, last_opened_at TEXT, last_closed_at TEXT,
            login_confirmed_at TEXT, PRIMARY KEY(root_code,platform))""")
        c.execute("""CREATE TABLE IF NOT EXISTS events(
            id INTEGER PRIMARY KEY, root_code TEXT NOT NULL, platform TEXT NOT NULL,
            event TEXT NOT NULL, happened_at TEXT NOT NULL, note TEXT)""")
        c.commit()
    os.chmod(DB, 0o600)

def path_for(root, platform):
    return PROFILE_ROOT / root / platform

def event(root, platform, name, note=""):
    ensure()
    stamp = now()
    with sqlite3.connect(DB) as c:
        c.execute("INSERT INTO events(root_code,platform,event,happened_at,note) VALUES(?,?,?,?,?)",
                  (root, platform, name, stamp, note[:160]))
        field = {"opened":"last_opened_at","closed":"last_closed_at",
                 "login_confirmed":"login_confirmed_at"}.get(name)
        if field:
            c.execute(f"UPDATE sessions SET {field}=? WHERE root_code=? AND platform=?",
                      (stamp, root, platform))
        c.commit()
    os.chmod(DB, 0o600)

def init_root(root):
    ensure()
    for platform in PLATFORMS:
        path = path_for(root, platform)
        path.mkdir(parents=True, exist_ok=True, mode=0o700)
        os.chmod(path, 0o700)
        with sqlite3.connect(DB) as c:
            c.execute("INSERT OR IGNORE INTO sessions(root_code,platform,profile_path,created_at) VALUES(?,?,?,?)",
                      (root, platform, str(path), now()))
            c.commit()
        print(f"READY {root}/{platform}: {path}")
    os.chmod(DB, 0o600)

def history_count(path):
    for hist in (path/"Default"/"History", path/"History"):
        if hist.is_file():
            try:
                with sqlite3.connect("file:"+str(hist)+"?mode=ro", uri=True, timeout=1) as c:
                    return str(c.execute("SELECT COUNT(*) FROM urls").fetchone()[0])
            except Exception:
                return "busy/unavailable"
    return "not-created-yet"

def show_status(root=None):
    ensure()
    with sqlite3.connect(DB) as c:
        query = "SELECT root_code,platform,profile_path,created_at,last_opened_at,last_closed_at,login_confirmed_at FROM sessions"
        rows = c.execute(query + (" WHERE root_code=? ORDER BY platform" if root else " ORDER BY root_code,platform"),
                         (root,) if root else ()).fetchall()
    if not rows:
        print("No profiles. Run init --root ROOT_0001")
    for r,p,raw,created,opened,closed,confirmed in rows:
        path = Path(raw)
        print(f"{r}/{p} | created={created} | opened={opened or '-'} | closed={closed or '-'}")
        print(f"  operator_login_confirmation={confirmed or '-'} | browser_history_entries={history_count(path)}")

def open_session(root, platform, headless):
    ensure()
    path = path_for(root, platform)
    if not path.is_dir():
        raise SystemExit("Profile missing. Run init first.")
    if not headless and not os.environ.get("DISPLAY") and sys.platform != "win32":
        raise SystemExit("No graphical DISPLAY. Run from an authorized desktop display; --headless is only for an already authenticated profile.")
    ctx = None
    event(root, platform, "opened", "persistent Chromium profile opened")
    print(f"Opening {root}/{platform}; persistent cookies and browser history are retained.")
    print("Sign in manually using the platform's normal login and MFA; no passwords or codes are stored by this tool.")
    try:
        with sync_playwright() as p:
            ctx = p.chromium.launch_persistent_context(
                user_data_dir=str(path), headless=headless,
                args=["--no-first-run","--no-default-browser-check"])
            page = ctx.pages[0] if ctx.pages else ctx.new_page()
            page.goto(PLATFORMS[platform], wait_until="domcontentloaded", timeout=60000)
            print("Session open. Press Ctrl+C in this terminal when finished.")
            while True:
                time.sleep(1)
    except KeyboardInterrupt:
        print("Closing browser cleanly.")
    finally:
        if ctx:
            ctx.close()
        event(root, platform, "closed", "persistent Chromium profile closed")
        print("Session closed; profile files remain on disk.")

def confirm_login(root, platform):
    ensure()
    with sqlite3.connect(DB) as c:
        found = c.execute("SELECT 1 FROM sessions WHERE root_code=? AND platform=?",(root,platform)).fetchone()
    if not found:
        raise SystemExit("Profile not initialized.")
    event(root, platform, "login_confirmed", "operator-confirmed; not independently verified")
    print(f"Recorded operator confirmation: {root}/{platform}")

def main():
    p = argparse.ArgumentParser(description="Awtad separated persistent social sessions")
    sub = p.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("init"); a.add_argument("--root", required=True)
    b = sub.add_parser("status"); b.add_argument("--root")
    c = sub.add_parser("open"); c.add_argument("--root", required=True)
    c.add_argument("--platform", required=True, choices=PLATFORMS); c.add_argument("--headless", action="store_true")
    d = sub.add_parser("confirm-login"); d.add_argument("--root", required=True)
    d.add_argument("--platform", required=True, choices=PLATFORMS)
    args = p.parse_args()
    if args.cmd == "init": init_root(valid_root(args.root))
    elif args.cmd == "status": show_status(valid_root(args.root) if args.root else None)
    elif args.cmd == "open": open_session(valid_root(args.root), args.platform, args.headless)
    elif args.cmd == "confirm-login": confirm_login(valid_root(args.root), args.platform)

if __name__ == "__main__":
    main()
