#!/usr/bin/env python3
"""
Unfavorite (remove) a property from Properstar favorites
"""
import asyncio
import json
import sys
from pathlib import Path
from playwright.async_api import async_playwright

async def unfavorite_property(url: str) -> dict:
    """
    Unfavorite a property on Properstar

    Args:
        url: Property URL to unfavorite

    Returns:
        dict with success status and message
    """
    script_dir = Path(__file__).parent
    auth_file = script_dir / "auth.json"

    if not auth_file.exists():
        return {
            'success': False,
            'message': 'Not logged in. Please run: python3 timed_login.py'
        }

    print(f"🗑️  Unfavoriting: {url}")

    try:
        async with async_playwright() as p:
            # Launch browser
            browser = await p.chromium.launch(headless=True)
            context = await browser.new_context(storage_state=str(auth_file))
            page = await context.new_page()

            # Navigate to property page
            print(f"   Opening property page...")
            await page.goto(url, timeout=30000)
            await page.wait_for_load_state('networkidle')

            # Look for the favorite button (heart icon)
            # The button might have different selectors depending on if it's favorited or not
            selectors = [
                'button[aria-label*="favorite" i]',
                'button[aria-label*="Remove from favorites" i]',
                'button[title*="favorite" i]',
                'button.favorite-button',
                '.favorite-btn',
                '[data-testid*="favorite"]',
                'button:has(svg[data-icon="heart"])'
            ]

            favorite_button = None
            for selector in selectors:
                try:
                    favorite_button = await page.wait_for_selector(selector, timeout=2000)
                    if favorite_button:
                        print(f"   Found favorite button with selector: {selector}")
                        break
                except:
                    continue

            if not favorite_button:
                # Try to find any button with heart icon
                print("   Searching for heart icon...")
                heart_buttons = await page.query_selector_all('button')
                for button in heart_buttons:
                    inner_html = await button.inner_html()
                    if 'heart' in inner_html.lower() or 'favorite' in inner_html.lower():
                        favorite_button = button
                        print(f"   Found heart button")
                        break

            if not favorite_button:
                await browser.close()
                return {
                    'success': False,
                    'message': 'Could not find favorite button on page'
                }

            # Check if it's currently favorited (filled heart)
            button_html = await favorite_button.inner_html()
            is_favorited = 'filled' in button_html.lower() or 'active' in button_html.lower()

            # If it's favorited, click to unfavorite
            if is_favorited:
                print(f"   Clicking to unfavorite...")
                await favorite_button.click()
                await page.wait_for_timeout(1000)  # Wait for the action to complete

                print(f"✅ Successfully unfavorited!")
                await browser.close()

                # Remove from enriched_data.json
                remove_from_data_file(url)

                return {
                    'success': True,
                    'message': 'Property removed from favorites'
                }
            else:
                print(f"⚠️  Property was not in favorites")
                await browser.close()

                # Still remove from data file even if not favorited
                remove_from_data_file(url)

                return {
                    'success': True,
                    'message': 'Property was not in favorites (already removed)'
                }

    except Exception as e:
        print(f"❌ Error unfavoriting property: {e}")
        return {
            'success': False,
            'message': f'Error: {str(e)}'
        }

def add_to_removed_list(url: str):
    """Add URL to the permanent removed properties blacklist"""
    script_dir = Path(__file__).parent
    removed_file = script_dir / "removed_properties.json"

    try:
        # Read existing blacklist
        if removed_file.exists():
            with open(removed_file, 'r', encoding='utf-8') as f:
                removed_urls = json.load(f)
        else:
            removed_urls = []

        # Add URL if not already in list
        if url not in removed_urls:
            removed_urls.append(url)

            # Save updated blacklist
            with open(removed_file, 'w', encoding='utf-8') as f:
                json.dump(removed_urls, f, indent=2, ensure_ascii=False)
            print(f"   ✅ Added to permanent removal blacklist")
        else:
            print(f"   ℹ️  Already in removal blacklist")

    except Exception as e:
        print(f"   ⚠️  Could not add to blacklist: {e}")

def remove_from_data_file(url: str):
    """Remove property from enriched_data.json and add to permanent blacklist"""
    script_dir = Path(__file__).parent
    data_file = script_dir / "enriched_data.json"

    # First, add to permanent blacklist so it won't be re-added
    add_to_removed_list(url)

    if not data_file.exists():
        print(f"   ⚠️  enriched_data.json not found - skipping data removal")
        return

    try:
        # Read current data
        with open(data_file, 'r', encoding='utf-8') as f:
            properties = json.load(f)

        # Filter out the property
        original_count = len(properties)
        properties = [p for p in properties if p.get('url') != url]
        new_count = len(properties)

        if original_count != new_count:
            # Save updated data
            with open(data_file, 'w', encoding='utf-8') as f:
                json.dump(properties, f, indent=2, ensure_ascii=False)
            print(f"   ✅ Removed from enriched_data.json ({original_count} → {new_count} properties)")
        else:
            print(f"   ℹ️  Property not found in enriched_data.json")

    except Exception as e:
        print(f"   ⚠️  Could not remove from enriched_data.json: {e}")

async def main():
    if len(sys.argv) < 2:
        print("Usage: python3 unfavorite_property.py <property_url>")
        print("Example: python3 unfavorite_property.py https://www.properstar.nl/listing/12345")
        sys.exit(1)

    url = sys.argv[1]
    result = await unfavorite_property(url)

    if result['success']:
        print(f"\n✅ {result['message']}")
        sys.exit(0)
    else:
        print(f"\n❌ {result['message']}")
        sys.exit(1)

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