"""
Move misplaced pins to their correct boards.
Scrapes each board, detects correct category from title, moves any that are wrong.
Run inside the pinterest-scheduler container.
"""
import sys, time, json
from pathlib import Path
sys.path.insert(0, '/app')
from pinterest.client import PinterestClient

data_dir = Path('/app/data/pinterest')

BOARD_KEY_TO_NAME = {
    'ghostbusters': 'Ghostbusters Cosplay & Equipment',
    'bttf': 'Back to the Future Replicas',
    'demon_slayer': 'Demon Slayer Art & Collectibles',
    'arcade_retro': 'Retro Arcade & Synthwave Art',
    'anime': 'Anime Posters & Wall Art',
    'anime_merch': 'Anime Merchandise & Gifts',
    'rmpropworks': 'RMPropWorks Studio: Behind the Scenes',
}

# URL slugs for each board
BOARD_URLS = {
    'bttf':         'https://www.pinterest.com/rmacsparran/back-to-the-future-replicas/',
    'ghostbusters': 'https://www.pinterest.com/rmacsparran/ghostbusters-cosplay-equipment/',
    'rmpropworks':  'https://www.pinterest.com/rmacsparran/rmpropworks-studio-behind-the-scenes/',
}

THEME_KEYWORDS = {
    'ghostbusters': ['ghostbusters', 'proton pack', 'ecto', 'ghost trap', 'stay puft', 'slimer'],
    'bttf': ['back to the future', 'bttf', 'delorean', 'flux capacitor', 'time circuits', '88 mph'],
    'demon_slayer': ['demon slayer', 'kimetsu', 'breathing', 'hashira', 'tanjiro', 'nezuko',
                     'rengoku', 'zenitsu', 'inosuke', 'giyu', 'shinobu', 'mitsuri', 'muichiro',
                     'obanai', 'sanemi', 'gyomei', 'akaza', 'douma', 'kokushibo'],
    'arcade_retro': ['arcade', 'synthwave', 'vaporwave', 'neon city', 'retro', '80s', 'pixel',
                     'neo-noir', 'rainy city', 'futuristic', 'cyberpunk'],
    'anime_merch': ['mug', 'gift', 'merchandise'],
    'anime': ['anime', 'manga', 'jjk', 'gojo', 'death note', 'solo leveling', 'naruto',
              'one piece', 'dragon ball', 'attack on titan', 'samurai', 'warrior', 'spirit energy',
              'cosmic warrior', 'ethereal', 'portrait'],
}


def detect_board(title: str) -> str:
    t = title.lower()
    for key in ['ghostbusters', 'bttf', 'demon_slayer', 'arcade_retro', 'anime_merch', 'anime']:
        for kw in THEME_KEYWORDS[key]:
            if kw in t:
                return key
    return 'rmpropworks'


def get_pins_from_board(page, board_url: str) -> list:
    """Navigate to a board and collect all pin titles + hrefs."""
    page.goto(board_url, timeout=60000)
    time.sleep(6)

    pins = []
    last_count = 0
    for _ in range(10):  # scroll up to 10 times
        page.evaluate('window.scrollBy(0, 1500)')
        time.sleep(2)
        elems = page.query_selector_all('[data-test-id="pin"]')
        if len(elems) == last_count:
            break
        last_count = len(elems)

    # Back to top and re-collect
    page.evaluate('window.scrollTo(0, 0)')
    time.sleep(2)
    elems = page.query_selector_all('[data-test-id="pin"]')
    print(f'  Found {len(elems)} pins')

    for elem in elems:
        try:
            title_el = elem.query_selector('[data-test-id="pinrep-footer-organic-title"]')
            title = (title_el.inner_text() or '').strip() if title_el else ''
            link_el = elem.query_selector('a[href*="/pin/"]')
            href = link_el.get_attribute('href') if link_el else ''
            if title:
                pins.append({'title': title, 'href': href, 'elem': elem})
        except:
            pass
    return pins


def move_pin(page, pin_href: str, target_board_name: str) -> bool:
    """Open a pin and change its board to target_board_name."""
    try:
        pin_url = f'https://www.pinterest.com{pin_href}' if pin_href.startswith('/') else pin_href
        page.goto(pin_url, timeout=30000)
        time.sleep(4)

        # Click the edit button (pencil)
        edit_btn = page.query_selector('[data-test-id="edit-pin-button"], [aria-label="Edit pin"], [data-test-id="edit-button"]')
        if not edit_btn:
            # Try finding via text
            for btn in page.query_selector_all('button'):
                aria = btn.get_attribute('aria-label') or ''
                if 'edit' in aria.lower():
                    edit_btn = btn
                    break

        if not edit_btn:
            print(f'    No edit button found on pin')
            return False

        edit_btn.click()
        time.sleep(3)

        # Find board selector in edit modal
        # Pinterest edit modal has a board dropdown
        board_btn = page.query_selector('[data-test-id="board-dropdown-select-button"], [data-test-id="board-select"]')
        if not board_btn:
            # Try finding by looking for the current board name
            for btn in page.query_selector_all('button, [role="button"]'):
                txt = (btn.inner_text() or '').strip()
                if any(name in txt for name in BOARD_KEY_TO_NAME.values()):
                    board_btn = btn
                    break

        if not board_btn:
            print(f'    No board selector found in edit modal')
            return False

        board_btn.click()
        time.sleep(2)

        # Search for or select target board
        search_input = page.query_selector('input[placeholder*="search" i], input[placeholder*="board" i]')
        if search_input:
            search_input.fill(target_board_name[:20])
            time.sleep(1)

        # Find and click target board option
        target_item = None
        for item in page.query_selector_all('[role="option"], [data-test-id="board-dropdown-item"]'):
            if target_board_name.lower() in (item.inner_text() or '').lower():
                target_item = item
                break

        if not target_item:
            print(f'    Board option not found: {target_board_name!r}')
            return False

        target_item.click()
        time.sleep(2)

        # Save
        save_btn = page.query_selector('[data-test-id="edit-pin-save-button"], button[type="submit"]')
        if save_btn:
            page.evaluate('el => el.click()', save_btn)
            time.sleep(3)
            print(f'    Moved to {target_board_name!r}')
            return True
        else:
            print(f'    No save button found')
            return False

    except Exception as ex:
        print(f'    Error moving pin: {ex}')
        return False


def main():
    moved = 0
    skipped = 0
    errors = 0

    with PinterestClient(data_dir) as client:
        client.is_authenticated()

        for current_key, board_url in BOARD_URLS.items():
            current_board_name = BOARD_KEY_TO_NAME[current_key]
            print(f'\n=== Checking board: {current_board_name} ===')

            pins = get_pins_from_board(client.page, board_url)

            for pin in pins:
                title = pin['title']
                correct_key = detect_board(title)
                correct_board = BOARD_KEY_TO_NAME[correct_key]

                if correct_key == current_key:
                    skipped += 1
                    continue

                print(f'  MOVE: {title[:50]!r}')
                print(f'    {current_board_name!r} → {correct_board!r}')

                if pin['href']:
                    ok = move_pin(client.page, pin['href'], correct_board)
                    if ok:
                        moved += 1
                    else:
                        errors += 1
                    # Go back to the board
                    client.page.goto(board_url, timeout=30000)
                    time.sleep(4)
                else:
                    print(f'    No href, skipping')
                    errors += 1

                time.sleep(1)

    print(f'\n=== DONE ===')
    print(f'Moved: {moved}  |  Already correct: {skipped}  |  Errors: {errors}')


if __name__ == '__main__':
    main()
