#!/usr/bin/env python3
"""
Daily Pinterest pin cleanup.
Scrolls to the BOTTOM (oldest pins) and deletes from there.
Preserves newest N pins (the fresh correct ones from current queue).
"""
import time
import logging
from pathlib import Path
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout

KEEP_NEWEST = 30      # Keep the most recent N pins (fresh queue)
MAX_DELETE = 50       # Max deletions per daily run
PROFILE_URL = "https://www.pinterest.com/rmacsparran/_created/"

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger(__name__)

def load_all_pins(page):
    """Scroll to bottom to load all pins, return full list"""
    prev_count = 0
    for _ in range(20):  # Max 20 scroll attempts
        page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
        time.sleep(3)
        pins = page.query_selector_all('[data-test-id="pin"]')
        log.info(f"  Loaded {len(pins)} pins after scroll")
        if len(pins) == prev_count:
            break
        prev_count = len(pins)
    return pins

def run_cleanup():
    data_dir = Path("/app/data/pinterest")
    state_file = data_dir / "browser_state.json"

    if not state_file.exists():
        log.error("No browser state found")
        return 0

    deleted = 0
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=['--no-sandbox','--disable-blink-features=AutomationControlled',
                  '--disable-dev-shm-usage','--disable-gpu','--disable-extensions']
        )
        context = browser.new_context(storage_state=str(state_file))
        page = context.new_page()
        page.set_default_timeout(20000)

        try:
            page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
            time.sleep(10)

            log.info("Loading all pins (scrolling to bottom)...")
            all_pins = load_all_pins(page)
            total = len(all_pins)
            log.info(f"Total pins found: {total}")

            if total <= KEEP_NEWEST:
                log.info(f"Only {total} pins — under keep threshold of {KEEP_NEWEST}. Nothing to delete.")
                browser.close()
                return 0

            to_delete = total - KEEP_NEWEST
            log.info(f"Will delete {min(to_delete, MAX_DELETE)} oldest pins (keeping newest {KEEP_NEWEST})")

            consecutive_fails = 0
            while deleted < min(to_delete, MAX_DELETE):
                try:
                    # Reload and scroll to bottom to find oldest pins
                    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
                    time.sleep(8)
                    pins = load_all_pins(page)

                    if not pins:
                        log.info("No more pins")
                        break

                    if len(pins) <= KEEP_NEWEST:
                        log.info(f"Down to {len(pins)} pins — at threshold. Done.")
                        break

                    # Delete the LAST pin (oldest)
                    target = pins[-1]
                    target.scroll_into_view_if_needed()
                    time.sleep(1)
                    target.click()
                    time.sleep(3)

                    more_btn = page.wait_for_selector('[data-test-id="closeup-action-bar-button"]', timeout=8000)
                    more_btn.click()
                    time.sleep(2)
                    edit_btn = page.wait_for_selector('[data-test-id="pin-action-dropdown-edit-pin"]', timeout=6000)
                    edit_btn.click()
                    time.sleep(3)
                    del_btn = page.wait_for_selector('[data-test-id="delete-pin-button"]', timeout=6000)
                    del_btn.click()
                    time.sleep(2)

                    try:
                        confirm = page.wait_for_selector('[data-test-id="confirm-button"], button:text("Delete")', timeout=3000)
                        confirm.click()
                        time.sleep(1)
                    except PlaywrightTimeout:
                        pass

                    deleted += 1
                    consecutive_fails = 0
                    log.info(f"Deleted oldest pin #{deleted} (was pin {len(pins)} of {len(pins)})")

                except (PlaywrightTimeout, Exception) as e:
                    consecutive_fails += 1
                    log.warning(f"Error ({consecutive_fails}): {str(e)[:80]}")
                    try:
                        page.keyboard.press('Escape')
                        time.sleep(2)
                    except:
                        pass
                    if consecutive_fails >= 5:
                        log.warning("5 consecutive failures — stopping")
                        break

        except Exception as e:
            log.error(f"Fatal: {e}")
        finally:
            try:
                browser.close()
            except:
                pass

    log.info(f"Cleanup done: {deleted} oldest pins deleted")
    return deleted

if __name__ == "__main__":
    run_cleanup()
