# Supporting Docs Flow - Integration Guide

This guide explains how to add a dedicated "Get Supporting Docs" flow for any new application (similar to Xero and Sage).

## Overview
- The app has a dedicated action `support_docs` that can be triggered during playback.
- For some applications, we branch to a specific flow (module) instead of the generic analyze-docs flow.
- Example implementations:
  - Xero (`app_id == 6`): Uses the attach/files subplaylist flow.
  - Sage (`app_id == 12`): Runs a configured subplaylist by ID via a small helper module.

## Steps to add a new application flow

1) Create a new module under `autoclicker/` for your application
- File name suggestion: `autoclicker/<app>_supporting_docs.py`
- Export a function `play_supporting_docs(app)` that encapsulates the flow. Example template:

```python
# autoclicker/myapp_supporting_docs.py
import os
import logging

def play_supporting_docs(app) -> None:
    """Execute MyApp supporting docs flow."""
    try:
        try:
            app.show_loader("Running MyApp supporting documents...")
        except Exception:
            pass

        # Option A: run a specific subplaylist by ID from env
        target_playlist_id = None
        env_val = os.getenv("MYAPP_SUPPORT_PLAYLIST_ID", "").strip()
        if env_val:
            try:
                target_playlist_id = int(env_val)
            except Exception:
                logging.error(f"[MyAppSupportDocs] MYAPP_SUPPORT_PLAYLIST_ID must be an integer; got '{env_val}'")

        # Fallback to the generic subplaylist target from constants if not set
        if target_playlist_id is None:
            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("MyApp: Subplaylist not configured (no valid playlist id)")
            except Exception:
                pass
            return

        # Execute target playlist inline
        from .playback import PlaybackManager
        manager = PlaybackManager(app)
        manager._execute_playlist_by_id(int(target_playlist_id))

    except Exception as e:
        logging.error(f"[MyAppSupportDocs] Flow failed: {e}")
    finally:
        try:
            app.hide_loader()
        except Exception:
            pass
```

2) Route playback to your new flow by `application_id`
- Update the `support_docs` handling in `autoclicker/playback.py`
- There are two relevant places to branch:
  - In the main playback loop where `act.get('action_type') == 'support_docs'`
  - In the helper method `_execute_support_docs_action`

Example change to the main loop case:

```python
# Inside PlaybackManager._playback_thread actions loop
elif act.get('action_type') == 'support_docs':
    try:
        # Existing logic
        try:
            app_id = getattr(self.app, 'current_application_id', None) or getattr(self.app, 'application_id', None)
            app_id = int(app_id) if app_id is not None else None
        except Exception:
            app_id = None

        if app_id == 6:
            self._execute_subplaylist_action({})  # Xero
        elif app_id == 12:
            from .sage_supporting_docs import play_supporting_docs as _sage_play
            _sage_play(self.app)
        elif app_id == <NEW_APP_ID>:
            from .myapp_supporting_docs import play_supporting_docs as _myapp_play
            _myapp_play(self.app)
        else:
            self._execute_analyze_docs_action()  # generic fallback
    except Exception:
        logging.exception("[Playback] support_docs action failed")
```

Example change to `_execute_support_docs_action`:

```python
# Inside PlaybackManager
def _execute_support_docs_action(self):
    """Dedicated Get Supporting Docs routing."""
    # ... pre-wait and resolve app_id ...

    if app_id == 6:
        from .xero_supporting_docs import play_supporting_docs as _xero_play
        _xero_play(self.app)
        return

    if app_id == 12:
        from .sage_supporting_docs import play_supporting_docs as _sage_play
        _sage_play(self.app)
        return

    if app_id == <NEW_APP_ID>:
        from .myapp_supporting_docs import play_supporting_docs as _myapp_play
        _myapp_play(self.app)
        return

    # generic fallback
    if not self._stop_requested:
        self._execute_analyze_docs_action()
```

3) Configure environment variables
- For flows that run a subplaylist by id, set the appropriate env var in `.env`:

```bash
# Sage example
SAGE_SUPPORT_PLAYLIST_NAME=61  # integer playlist id used by Sage flow

# Your new app example
MYAPP_SUPPORT_PLAYLIST_ID=58  # integer playlist id used by MyApp flow
```

- Optional: override global fallbacks in `autoclicker/constants.py` via env vars:
  - `SUBPLAYLIST_TARGET_PLAYLIST_ID`
  - `SUBPLAYLIST_FILES_*` and related if you leverage file-count branching

4) Verify database and playlists
- Ensure the target subplaylist exists in MySQL `playlists` with the right `application_id`.
- If using subplaylist features, confirm `sub_playlist_updates.sql` has been applied.

5) Test the flow
- Start the app, select a playlist for your application, and trigger "Get Supporting Docs".
- Confirm routing: your module runs for your `application_id`.
- Review logs in `logs/app_debug.log` or `logs/openai.log` if needed.

## Tips
- Keep your module focused on one responsibility (e.g., call a subplaylist or perform a specific click/analysis routine).
- Reuse existing helpers: `_execute_playlist_by_id`, `_execute_subplaylist_action`, OpenAI analyzer utilities, etc.
- For apps similar to Xero, consider reusing the attach/files dialog routine via `_execute_subplaylist_action`.
