"""
Sage Attachments Finder

Pure analyzer/clicker for the Sage attachments dialog. This module does NOT
run any playlists. It expects the attachments dialog to already be open.
"""

import os
import time
import json
import base64
import logging
import re
from typing import List, Dict
import pyautogui


# Note: No playlist-running helpers are defined here by design.


def get_attachment_link_words(app) -> Dict:
    """Detect attachment presence and names from the CURRENT dialog (no playlist).

    Returns a dict: {"modal_present": bool, "has_attachments": bool, "links": List[str]}.
    """
    return analyze_attachment_names_from_current_dialog(app)


def run_and_click_attachments(app, analyzer=None) -> List[str]:
    """Detect attachment names once and click only that many times (no replays).

    Returns the list of link words that were attempted to click.
    """
    # Do NOT replay any playlist here; assume the dialog is already open.
    result = analyze_attachment_names_from_current_dialog(app)
    links: List[str] = result.get("links", []) if isinstance(result, dict) else []
    if not links:
        return []

    # Analyzer for screenshot and Rekognition OCR only
    if analyzer is None:
        analyzer = getattr(app, 'screenshot_manager', None)
        analyzer = getattr(analyzer, 'openai_analyzer', None)
    if analyzer is None:
        return []

    # De-duplicate while preserving order
    seen = set()
    unique_links: List[str] = []
    for name in links:
        if name not in seen:
            seen.add(name)
            unique_links.append(name)

    # Configurable short wait between clicks for this lightweight flow
    try:
        wait_after_click = float(os.getenv("SAGE_SIMPLE_CLICK_WAIT_SEC", "2.0"))
    except Exception:
        wait_after_click = 2.0

    # Click each link exactly once using Rekognition coordinates only
    for name in unique_links:
        try:
            screenshot_path = analyzer.capture_full_resolution_screenshot()
            if not screenshot_path:
                continue
            coords = analyzer.find_text_coordinates_rekognition(screenshot_path, name)
            if not (isinstance(coords, (list, tuple)) and len(coords) == 2):
                continue
            x, y = int(coords[0]), int(coords[1])
            # Perform the click without triggering analyzer UI/tab logic
            try:
                restore = None
                try:
                    # Hide app if helper exists, but it has no tab logic
                    restore = getattr(analyzer, '_temporarily_hide_app', None)
                    if callable(restore):
                        restore = restore()
                except Exception:
                    restore = None
                pyautogui.click(x, y)
            finally:
                try:
                    if callable(restore):
                        restore()
                except Exception:
                    pass
            # One-shot check for Save/Confirm dialog; do not loop.
            try:
                from .modal_handler import click_save_dialog_once
                click_save_dialog_once(analyzer)
            except Exception:
                pass
            time.sleep(wait_after_click)
        except Exception:
            # Continue to next link on error
            pass

    # After processing all links, do a one-shot close dialog click if present
    try:
        from .modal_handler import click_close_dialog_once
        click_close_dialog_once(analyzer)
    except Exception:
        pass

    return unique_links


def analyze_attachment_names_from_current_dialog(app, analyzer=None) -> Dict:
    """Analyze the current screen for the attachments dialog and return presence + names.

    This function does NOT run any playlist.
    """
    try:
        # Acquire analyzer
        if analyzer is None:
            analyzer = getattr(app, 'screenshot_manager', None)
            analyzer = getattr(analyzer, 'openai_analyzer', None)
        if analyzer is None:
            try:
                app.status_var.set("Analyzer unavailable")
            except Exception:
                pass
            return {"modal_present": False, "has_attachments": False, "links": []}

        # Screenshot as data URL
        screenshot_path = analyzer.capture_full_resolution_screenshot()
        if not screenshot_path:
            try:
                app.status_var.set("Failed to capture screenshot")
            except Exception:
                pass
            return {"modal_present": False, "has_attachments": False, "links": []}

        with open(screenshot_path, 'rb') as f:
            img_b = f.read()
        img_b64 = base64.b64encode(img_b).decode('utf-8')
        image_url = f"data:image/png;base64,{img_b64}"

        # Build presence+names prompt
        try:
            sw, sh = analyzer._get_screen_size()
        except Exception:
            sw, sh = 1920, 1080
        try:
            from .prompt_builder import get_attachment_presence_and_names_prompt
            prompt = get_attachment_presence_and_names_prompt(sw, sh)
        except Exception:
            prompt = "Return JSON {modal_present, has_attachments, links[]} for attachments dialog."

        # Call model
        try:
            from .constants import OPENAI_VISION_TEMPERATURE
        except Exception:
            OPENAI_VISION_TEMPERATURE = 0.0
        try:
            content = analyzer._post_vision(
                prompt,
                image_url,
                max_tokens=800,
                temperature=float(OPENAI_VISION_TEMPERATURE),
            )
        except Exception as _e:
            try:
                analyzer.openai_logger.error(f"OpenAI API error: {_e}")
            except Exception:
                pass
            return {"modal_present": False, "has_attachments": False, "links": []}

        # Parse JSON object
        result = {"modal_present": False, "has_attachments": False, "links": []}
        try:
            start_idx = content.find('{'); end_idx = content.rfind('}') + 1
            if start_idx != -1 and end_idx != -1:
                obj = json.loads(content[start_idx:end_idx])
                result["modal_present"] = bool(obj.get("modal_present", False))
                result["has_attachments"] = bool(obj.get("has_attachments", False))
                links = obj.get("links") or []
                # Clean file names: remove "View (" prefix and closing ")" bracket
                cleaned_links = []
                for x in links:
                    if not isinstance(x, (str, int, float)):
                        continue
                    name = str(x).strip()
                    if not name:
                        continue
                    # Remove "View (" prefix (case-insensitive) and extract content from parentheses
                    # Match "View (" at the start (case-insensitive) followed by content and closing ")"
                    match = re.match(r'(?i)^view\s*\((.+)\)\s*$', name)
                    if match:
                        name = match.group(1).strip()
                    cleaned_links.append(name)
                result["links"] = cleaned_links
        except Exception:
            pass

        # UI feedback
        try:
            if not result["modal_present"]:
                app.status_var.set("Attachments dialog not found")
            elif not result["has_attachments"]:
                app.status_var.set("No attachments to download")
            else:
                joined = ", ".join(result["links"][:6])
                if len(result["links"]) > 6:
                    joined += ", ..."
                app.status_var.set(f"Found {len(result['links'])} attachment(s): {joined}")
        except Exception:
            pass

        return result
    except Exception as e:
        logging.error(f"[SageAttachments] Analyze current dialog failed: {e}")
        return {"modal_present": False, "has_attachments": False, "links": []}

