""" Outgoing webmention link extraction and queueing Per background-worker.md and architect's answers: - Extract links from rendered HTML (not markdown) - Extract only elements, exclude
 and  blocks
- Queue max 10 links per note per operation
- Priority: in_reply_to first, then document order

References:
    - Background Worker Design: /docs/design/v1.6.0/background-worker.md
    - API Contract: /docs/design/v1.6.0/api-contract.md
"""

import logging
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Optional, Set
from lxml import html as lxml_html
from urllib.parse import urlparse


logger = logging.getLogger(__name__)


def extract_links_from_html(html_content: str, exclude_code_blocks: bool = True) -> list[str]:
    """
    Extract links from HTML content.

    Per architect's answer to Q1:
    - Extract from rendered HTML (not markdown)
    - Extract  elements only
    - Exclude links in 
 and  blocks
    - Return in document order

    Args:
        html_content: Rendered HTML content
        exclude_code_blocks: If True, skip links in 
 and  (default: True)

    Returns:
        List of URLs in document order
    """
    if not html_content or not html_content.strip():
        return []

    try:
        # Parse HTML
        doc = lxml_html.fromstring(html_content)

        if exclude_code_blocks:
            # Remove 
 and  elements before extracting links
            for element in doc.xpath('//pre | //code'):
                element.getparent().remove(element)

        # Extract all  attributes in document order
        links = doc.xpath('//a/@href')

        # Filter to valid absolute URLs (http/https)
        absolute_links = []
        for link in links:
            parsed = urlparse(link)
            if parsed.scheme in ('http', 'https') and parsed.netloc:
                absolute_links.append(link)

        return absolute_links

    except Exception as e:
        logger.warning(f"Failed to parse HTML for link extraction: {e}")
        return []


def queue_webmentions_for_note(
    db_path: Path,
    note_id: int,
    note_url: str,
    content_html: str,
    in_reply_to: Optional[str] = None,
    old_content_html: Optional[str] = None  # Phase 6: update semantics
) -> int:
    """
    Extract links and queue webmentions for a note.

    Per architect's answers (Phase 6):
    - Called from notes.py AFTER successful database commit
    - For updates: diff old vs new URLs, queue for new/existing/removed
    - For creates: queue for all URLs in content
    - Max 10 webmentions per operation
    - Priority: in_reply_to URL first, then document order
    - Webmention sending is best-effort; failures do not affect note creation

    Args:
        db_path: Path to SQLite database
        note_id: Database ID of the note
        note_url: Full URL of the published note
        content_html: Rendered HTML content (None if unpublishing)
        in_reply_to: Reply-to URL (if reply post)
        old_content_html: Previous HTML (for update diff, Phase 6)

    Returns:
        Number of webmentions queued
    """
    # Phase 6: Implement URL diffing for updates
    if old_content_html is not None:
        # This is an update - compute URL diff
        old_links = set(extract_links_from_html(old_content_html))

        # Handle unpublishing case (content_html is None)
        if content_html is None:
            # Unpublishing - queue for all old URLs (they're all removed)
            new_links = set()
        else:
            new_links = set(extract_links_from_html(content_html))

        # Compute sets for URL diffing
        new_urls = new_links - old_links  # In new, not in old
        existing_urls = new_links & old_links  # In both (re-validate)
        removed_urls = old_links - new_links  # In old, not in new

        # Build target list: new + existing + removed
        # (All need webmentions per W3C spec)
        all_update_urls = list(new_urls) + list(existing_urls) + list(removed_urls)

        # Add in_reply_to if changed
        target_urls = []
        if in_reply_to and in_reply_to not in all_update_urls:
            target_urls.append(in_reply_to)

        # Add the diffed URLs
        target_urls.extend(all_update_urls)

        # Limit to 10
        target_urls = target_urls[:10]

    else:
        # This is a create (no old content) - use original logic
        links = extract_links_from_html(content_html) if content_html else []

        # Build priority-ordered list of target URLs
        target_urls = []

        # 1. in_reply_to gets highest priority
        if in_reply_to:
            target_urls.append(in_reply_to)

        # 2. Add extracted links in document order (deduplicated)
        seen = {in_reply_to} if in_reply_to else set()
        for link in links:
            if link not in seen:
                target_urls.append(link)
                seen.add(link)

        # 3. Limit to 10 webmentions per operation
        target_urls = target_urls[:10]

    if not target_urls:
        logger.debug(f"No links to send webmentions for note {note_id}")
        return 0

    # Queue webmentions
    queued = 0
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        for target_url in target_urls:
            try:
                # Use UPSERT to handle duplicate sends
                # Phase 6: Force endpoint rediscovery per W3C MUST requirement
                cursor.execute("""
                    INSERT INTO webmention_queue
                        (source_url, target_url, source_note_id, status, created_at)
                    VALUES (?, ?, ?, 'pending', CURRENT_TIMESTAMP)
                    ON CONFLICT(source_url, target_url) DO UPDATE SET
                        status = 'pending',
                        retry_count = 0,
                        next_retry_at = NULL,
                        last_error = NULL,
                        endpoint_url = NULL,
                        created_at = CURRENT_TIMESTAMP
                """, (note_url, target_url, note_id))

                queued += 1

            except Exception as e:
                logger.warning(
                    f"Failed to queue webmention {note_url} -> {target_url}: {e}"
                )

        conn.commit()
        conn.close()

        logger.info(f"Queued {queued} webmentions for note {note_id}")

    except Exception as e:
        logger.error(f"Failed to queue webmentions for note {note_id}: {e}")

    return queued