"""
Sage Supporting Documents helper functions.

Behavior: when invoked, run a configured subplaylist by ID.
- Primary source: environment variable SAGE_SUPPORT_PLAYLIST_NAME (treated as an integer ID)
- Fallback: constants.SUBPLAYLIST_TARGET_PLAYLIST_ID
"""

import os
import logging
import time
import base64
import json


def play_supporting_docs(app) -> None:
    """Execute the Sage supporting documents flow by running a subplaylist.

    Current behavior:
    - Determine target subplaylist id from env `SAGE_SUPPORT_PLAYLIST_NAME` (treated as integer)
    - If not provided or invalid, fall back to constants.SUBPLAYLIST_TARGET_PLAYLIST_ID
    - Execute that playlist inline via PlaybackManager
    """
    try:
        # Loader message for user feedback
        try:
            app.show_loader("Running Sage supporting documents...")
        except Exception:
            pass

        # Read target playlist id from environment (treat as integer)
        target_playlist_id = None
        env_val = os.getenv("SAGE_SUPPORT_PLAYLIST_NAME", "").strip()
        if env_val:
            try:
                target_playlist_id = int(env_val)
            except Exception:
                logging.error(f"[SageSupportDocs] SAGE_SUPPORT_PLAYLIST_NAME must be an integer id; got '{env_val}'")

        if target_playlist_id is None:
            # Fallback to configured target playlist id from constants
            try:
                from .constants import SUBPLAYLIST_TARGET_PLAYLIST_ID
                target_playlist_id = int(SUBPLAYLIST_TARGET_PLAYLIST_ID)
            except Exception:
                target_playlist_id = None

        if target_playlist_id is None:
            try:
                if hasattr(app, "status_var"):
                    app.status_var.set("Sage: Subplaylist not configured (no valid playlist id)")
            except Exception:
                pass
            return

        # Execute target playlist inline using PlaybackManager
        try:
            from .playback import PlaybackManager
            manager = PlaybackManager(app)
            manager._execute_playlist_by_id(int(target_playlist_id))
        except Exception as e:
            logging.error(f"[SageSupportDocs] Failed to execute subplaylist id={target_playlist_id}: {e}")
            return
        finally:
            try:
                # Ensure UI status reflects active playback unless paused elsewhere
                if hasattr(app, 'status_var') and app.status_var.get() != 'Paused':
                    app.status_var.set('Playing')
            except Exception:
                pass

        # After the subplaylist completes, use the new attachments finder flow
        try:
            try:
                wait_time = float(os.getenv("SCREENSHOT_PRE_DELAY_SEC", "5.0"))
            except Exception:
                wait_time = 5.0
            time.sleep(wait_time)

            # Detect dialog, get names ONCE, then click exactly those via Rekognition
            from .sage_attachments_finder import analyze_attachment_names_from_current_dialog
            from .sage_attachments_finder import run_and_click_attachments

            result = analyze_attachment_names_from_current_dialog(app)
            links = (result.get('links') if isinstance(result, dict) else []) or []
            if links:
                run_and_click_attachments(app)
            else:
                # If no links were found, attempt to close the dialog once
                try:
                    from .modal_handler import click_close_dialog_once
                    analyzer = getattr(app, 'screenshot_manager', None)
                    analyzer = getattr(analyzer, 'openai_analyzer', None)
                    if analyzer is not None:
                        click_close_dialog_once(analyzer)
                except Exception:
                    pass
        except Exception as e:
            logging.error(f"[SageSupportDocs] Post-subplaylist attachments flow failed: {e}")
    finally:
        # Always hide loader
        try:
            app.hide_loader()
        except Exception:
            pass
