"""
GUI Modifications for Salesforce Integration
============================================
Modifications and additions to integrate Salesforce workflows into the existing FoundryMatch GUI.
This file should be used to modify the existing gui.py file.
"""

import asyncio
import logging
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import pandas as pd

# Import Salesforce modules (these would be added to the existing imports in gui.py)
from .core import SalesforceIntegration
from .gui_integration import (
    SalesforceConnectionDialog,
)
from .workflows import (
    SalesforceWorkflowEngine,
    WorkflowResult,
    PreviewResult,
    create_dedupe_workflow_config,
    create_lead_to_account_config,
)

log = logging.getLogger(__name__)


class SalesforceWorkflowDialog(tk.Toplevel):
    """Dialog for configuring and executing Salesforce workflows."""

    def __init__(
        self,
        parent,
        sf_integration: SalesforceIntegration,
        matches_df: pd.DataFrame,
        workflow_type: str = "dedupe",
    ):
        super().__init__(parent)
        self.parent = parent
        self.sf_integration = sf_integration
        self.matches_df = matches_df
        self.workflow_type = workflow_type
        self.workflow_engine = SalesforceWorkflowEngine(sf_integration)
        self.preview_result = None
        self.execution_result = None

        # Dialog setup
        self.title(f"Salesforce {workflow_type.title()} Workflow")
        self.geometry("800x700")
        self.transient(parent)
        self.grab_set()

        # Variables
        self.dry_run_var = tk.BooleanVar(value=True)
        self.backup_enabled_var = tk.BooleanVar(value=True)
        self.object_name_var = tk.StringVar(
            value="Lead" if workflow_type == "lead_to_account" else "Account"
        )

        # Workflow-specific variables
        if workflow_type == "dedupe":
            self.master_strategy_var = tk.StringVar(value="oldest")
            self.delete_duplicates_var = tk.BooleanVar(value=False)
        elif workflow_type == "lead_to_account":
            self.target_field_var = tk.StringVar(value="AccountId")
            self.confidence_threshold_var = tk.DoubleVar(value=85.0)
            self.update_status_var = tk.BooleanVar(value=True)

        self._build_ui()
        self._center_window()

    def _build_ui(self):
        """Build the workflow dialog UI."""
        # Main container with notebook
        main_frame = ttk.Frame(self, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # Title
        title_text = (
            f"Salesforce {self.workflow_type.replace('_', '-to-').title()} Workflow"
        )
        title_label = ttk.Label(
            main_frame, text=title_text, font=("TkDefaultFont", 14, "bold")
        )
        title_label.pack(pady=(0, 20))

        # Notebook for different sections
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True, pady=(0, 20))

        # Configuration tab
        config_frame = ttk.Frame(notebook)
        notebook.add(config_frame, text="Configuration")
        self._build_config_tab(config_frame)

        # Preview tab
        preview_frame = ttk.Frame(notebook)
        notebook.add(preview_frame, text="Preview")
        self._build_preview_tab(preview_frame)

        # Execution tab
        execution_frame = ttk.Frame(notebook)
        notebook.add(execution_frame, text="Execution")
        self._build_execution_tab(execution_frame)

        # Button bar
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X)

        # Left side - workflow buttons
        left_buttons = ttk.Frame(button_frame)
        left_buttons.pack(side=tk.LEFT)

        self.preview_btn = ttk.Button(
            left_buttons, text="Preview Changes", command=self._preview_workflow
        )
        self.preview_btn.pack(side=tk.LEFT, padx=(0, 10))

        self.execute_btn = ttk.Button(
            left_buttons,
            text="Execute Workflow",
            command=self._execute_workflow,
            style="Primary.TButton",
            state=tk.DISABLED,
        )
        self.execute_btn.pack(side=tk.LEFT)

        # Right side - dialog buttons
        right_buttons = ttk.Frame(button_frame)
        right_buttons.pack(side=tk.RIGHT)

        ttk.Button(right_buttons, text="Close", command=self.destroy).pack(
            side=tk.RIGHT
        )

    def _build_config_tab(self, parent):
        """Build configuration tab."""
        # General settings
        general_frame = ttk.LabelFrame(parent, text="General Settings", padding="15")
        general_frame.pack(fill=tk.X, pady=(0, 15))

        # Safety settings
        ttk.Checkbutton(
            general_frame,
            text="Dry Run (Preview only, no changes)",
            variable=self.dry_run_var,
        ).pack(anchor=tk.W, pady=2)

        ttk.Checkbutton(
            general_frame,
            text="Create backup before changes",
            variable=self.backup_enabled_var,
        ).pack(anchor=tk.W, pady=2)

        # Object selection
        obj_frame = ttk.Frame(general_frame)
        obj_frame.pack(fill=tk.X, pady=(10, 0))
        ttk.Label(obj_frame, text="Salesforce Object:").pack(side=tk.LEFT, padx=(0, 10))
        ttk.Entry(obj_frame, textvariable=self.object_name_var, width=20).pack(
            side=tk.LEFT
        )

        # Workflow-specific settings
        if self.workflow_type == "dedupe":
            self._build_dedupe_config(parent)
        elif self.workflow_type == "lead_to_account":
            self._build_lead_to_account_config(parent)

    def _build_dedupe_config(self, parent):
        """Build deduplication-specific configuration."""
        dedupe_frame = ttk.LabelFrame(
            parent, text="Deduplication Settings", padding="15"
        )
        dedupe_frame.pack(fill=tk.X, pady=(0, 15))

        # Master record strategy
        strategy_frame = ttk.Frame(dedupe_frame)
        strategy_frame.pack(fill=tk.X, pady=5)
        ttk.Label(strategy_frame, text="Master Record Strategy:").pack(
            side=tk.LEFT, padx=(0, 10)
        )

        strategy_combo = ttk.Combobox(
            strategy_frame,
            textvariable=self.master_strategy_var,
            values=["oldest", "newest", "most_complete"],
            state="readonly",
            width=15,
        )
        strategy_combo.pack(side=tk.LEFT)

        # Delete duplicates option
        ttk.Checkbutton(
            dedupe_frame,
            text="Delete duplicate records (instead of merge)",
            variable=self.delete_duplicates_var,
        ).pack(anchor=tk.W, pady=5)

        # Warning about deletion
        warning_label = ttk.Label(
            dedupe_frame,
            text="⚠️ Warning: Deletion cannot be undone. Merge is recommended for safety.",
            foreground="red",
        )
        warning_label.pack(anchor=tk.W, pady=2)

    def _build_lead_to_account_config(self, parent):
        """Build Lead-to-Account specific configuration."""
        lead_frame = ttk.LabelFrame(
            parent, text="Lead-to-Account Settings", padding="15"
        )
        lead_frame.pack(fill=tk.X, pady=(0, 15))

        # Target lookup field
        field_frame = ttk.Frame(lead_frame)
        field_frame.pack(fill=tk.X, pady=5)
        ttk.Label(field_frame, text="Target Lookup Field:").pack(
            side=tk.LEFT, padx=(0, 10)
        )
        ttk.Entry(field_frame, textvariable=self.target_field_var, width=20).pack(
            side=tk.LEFT
        )

        # Confidence threshold
        threshold_frame = ttk.Frame(lead_frame)
        threshold_frame.pack(fill=tk.X, pady=5)
        ttk.Label(threshold_frame, text="Minimum Confidence:").pack(
            side=tk.LEFT, padx=(0, 10)
        )
        ttk.Spinbox(
            threshold_frame,
            textvariable=self.confidence_threshold_var,
            from_=0,
            to=100,
            increment=5,
            width=10,
        ).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Label(threshold_frame, text="%").pack(side=tk.LEFT)

        # Update lead status
        ttk.Checkbutton(
            lead_frame,
            text="Update Lead status to 'Qualified'",
            variable=self.update_status_var,
        ).pack(anchor=tk.W, pady=5)

    def _build_preview_tab(self, parent):
        """Build preview tab."""
        # Preview results area
        self.preview_text = tk.Text(parent, wrap=tk.WORD, height=20, width=80)
        self.preview_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        preview_scroll = ttk.Scrollbar(parent, command=self.preview_text.yview)
        preview_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.preview_text.config(yscrollcommand=preview_scroll.set)

        # Initial message
        self.preview_text.insert(
            tk.END, "Click 'Preview Changes' to analyze the workflow impact..."
        )
        self.preview_text.config(state=tk.DISABLED)

    def _build_execution_tab(self, parent):
        """Build execution tab."""
        # Progress section
        progress_frame = ttk.LabelFrame(parent, text="Execution Progress", padding="15")
        progress_frame.pack(fill=tk.X, padx=10, pady=10)

        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            progress_frame, variable=self.progress_var, maximum=100
        )
        self.progress_bar.pack(fill=tk.X, pady=(0, 10))

        self.progress_label = ttk.Label(progress_frame, text="Ready to execute")
        self.progress_label.pack(anchor=tk.W)

        # Results section
        results_frame = ttk.LabelFrame(parent, text="Execution Results", padding="15")
        results_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        self.results_text = tk.Text(results_frame, wrap=tk.WORD, height=10, width=80)
        self.results_text.pack(fill=tk.BOTH, expand=True)
        self.results_text.config(state=tk.DISABLED)

    def _preview_workflow(self):
        """Preview the workflow changes."""
        self.preview_btn.config(state=tk.DISABLED, text="Generating Preview...")

        def preview_async():
            try:
                # Create workflow configuration
                if self.workflow_type == "dedupe":
                    config = create_dedupe_workflow_config(
                        object_name=self.object_name_var.get(),
                        master_record_strategy=self.master_strategy_var.get(),
                        delete_duplicates=self.delete_duplicates_var.get(),
                        dry_run=True,  # Always dry run for preview
                        backup_enabled=self.backup_enabled_var.get(),
                    )
                else:
                    config = create_lead_to_account_config(
                        target_lookup_field=self.target_field_var.get(),
                        match_confidence_threshold=self.confidence_threshold_var.get(),
                        update_lead_status=self.update_status_var.get(),
                        dry_run=True,
                        backup_enabled=self.backup_enabled_var.get(),
                    )

                # Execute preview
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

                if self.workflow_type == "dedupe":
                    preview_result = loop.run_until_complete(
                        self.workflow_engine.preview_dedupe_workflow(
                            config, self.matches_df
                        )
                    )
                else:
                    preview_result = loop.run_until_complete(
                        self.workflow_engine.preview_lead_to_account_workflow(
                            config, self.matches_df
                        )
                    )

                loop.close()
                self.after(0, self._display_preview_results, preview_result)

            except Exception as e:
                log.error(f"Preview error: {e}", exc_info=True)
                self.after(0, self._display_preview_error, str(e))

        threading.Thread(target=preview_async, daemon=True).start()

    def _display_preview_results(self, preview_result: PreviewResult):
        """Display preview results."""
        self.preview_result = preview_result

        # Format preview text
        preview_text = f"""Workflow Preview Results
========================

Total Candidates: {preview_result.total_candidates:,}
Estimated Updates: {preview_result.estimated_updates:,}
Estimated API Calls: {preview_result.estimated_api_calls:,}

Confidence Distribution:
"""

        for confidence_level, count in preview_result.confidence_distribution.items():
            preview_text += f"  {confidence_level}: {count:,}\n"

        if preview_result.estimated_api_calls > 0:
            usage_pct = (
                preview_result.estimated_api_calls / 15000
            ) * 100  # Assuming 15k daily limit
            if usage_pct >= 80:
                preview_text += f"\n🚨 HIGH API USAGE: {preview_result.estimated_api_calls:,} calls ({usage_pct:.1f}% of limit)\n"
            elif usage_pct >= 50:
                preview_text += f"\n⚠️ MODERATE API USAGE: {preview_result.estimated_api_calls:,} calls ({usage_pct:.1f}% of limit)\n"
            else:
                preview_text += f"\n✅ API Usage: {preview_result.estimated_api_calls:,} calls ({usage_pct:.1f}% of limit)\n"

        if preview_result.potential_issues:
            preview_text += "\n⚠️ Potential Issues:\n"
            for issue in preview_result.potential_issues:
                preview_text += f"  • {issue}\n"

        if preview_result.sample_matches:
            preview_text += (
                f"\nSample Matches (first {len(preview_result.sample_matches)}):\n"
            )
            for i, match in enumerate(preview_result.sample_matches[:5], 1):
                if self.workflow_type == "dedupe":
                    preview_text += f"  {i}. Master: {match.get('master_id')} -> Duplicates: {len(match.get('duplicate_ids', []))}\n"
                else:
                    preview_text += f"  {i}. Lead: {match.get('lead_name')} -> Account: {match.get('account_name')} ({match.get('confidence'):.1f}%)\n"

        # Update preview display
        self.preview_text.config(state=tk.NORMAL)
        self.preview_text.delete(1.0, tk.END)
        self.preview_text.insert(1.0, preview_text)
        self.preview_text.config(state=tk.DISABLED)

        # Enable execute button if no critical issues
        critical_issues = [
            issue
            for issue in preview_result.potential_issues
            if "exceed API limits" in issue
        ]
        if not critical_issues:
            self.execute_btn.config(state=tk.NORMAL)

        self.preview_btn.config(state=tk.NORMAL, text="Preview Changes")

    def _display_preview_error(self, error: str):
        """Display preview error."""
        self.preview_text.config(state=tk.NORMAL)
        self.preview_text.delete(1.0, tk.END)
        self.preview_text.insert(1.0, f"Preview Error:\n{error}")
        self.preview_text.config(state=tk.DISABLED)
        self.preview_btn.config(state=tk.NORMAL, text="Preview Changes")

    def _execute_workflow(self):
        """Execute the workflow."""
        if not self.preview_result:
            messagebox.showwarning("No Preview", "Please run preview first")
            return

        # Confirmation dialog
        if not self.dry_run_var.get():
            if not messagebox.askyesno(
                "Confirm Execution",
                f"This will update {self.preview_result.estimated_updates:,} records in Salesforce.\n\n"
                "Are you sure you want to proceed?",
            ):
                return

        self.execute_btn.config(state=tk.DISABLED, text="Executing...")
        self.progress_var.set(0)
        self.progress_label.config(text="Starting workflow execution...")

        def execute_async():
            try:
                # Create workflow configuration
                if self.workflow_type == "dedupe":
                    config = create_dedupe_workflow_config(
                        object_name=self.object_name_var.get(),
                        master_record_strategy=self.master_strategy_var.get(),
                        delete_duplicates=self.delete_duplicates_var.get(),
                        dry_run=self.dry_run_var.get(),
                        backup_enabled=self.backup_enabled_var.get(),
                    )
                else:
                    config = create_lead_to_account_config(
                        target_lookup_field=self.target_field_var.get(),
                        match_confidence_threshold=self.confidence_threshold_var.get(),
                        update_lead_status=self.update_status_var.get(),
                        dry_run=self.dry_run_var.get(),
                        backup_enabled=self.backup_enabled_var.get(),
                    )

                # Progress callback
                async def progress_callback(message: str, percent: float):
                    self.after(0, self._update_progress, message, percent)

                # Execute workflow
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

                if self.workflow_type == "dedupe":
                    result = loop.run_until_complete(
                        self.workflow_engine.execute_dedupe_workflow(
                            config, self.matches_df, progress_callback
                        )
                    )
                else:
                    result = loop.run_until_complete(
                        self.workflow_engine.execute_lead_to_account_workflow(
                            config, self.matches_df, progress_callback
                        )
                    )

                loop.close()
                self.after(0, self._display_execution_results, result)

            except Exception as e:
                log.error(f"Execution error: {e}", exc_info=True)
                self.after(0, self._display_execution_error, str(e))

        threading.Thread(target=execute_async, daemon=True).start()

    def _update_progress(self, message: str, percent: float):
        """Update progress display."""
        self.progress_var.set(percent)
        self.progress_label.config(text=message)

    def _display_execution_results(self, result: WorkflowResult):
        """Display execution results."""
        self.execution_result = result

        # Format results text
        status = "✅ Success" if result.success else "❌ Failed"
        results_text = f"""Workflow Execution Results
==========================

Status: {status}
Records Processed: {result.records_processed:,}
Records Updated: {result.records_updated:,}
Records Merged: {result.records_merged:,}
API Calls Used: {result.api_calls_used:,}
Execution Time: {result.execution_time:.1f} seconds

"""

        if result.backup_file:
            results_text += f"Backup File: {result.backup_file}\n"

        if result.error_message:
            results_text += f"\nError: {result.error_message}\n"

        if result.audit_log:
            results_text += f"\nAudit Log Entries: {len(result.audit_log)}\n"

        # Update results display
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.insert(1.0, results_text)
        self.results_text.config(state=tk.DISABLED)

        # Reset execution button
        self.execute_btn.config(state=tk.NORMAL, text="Execute Workflow")
        self.progress_var.set(100)
        self.progress_label.config(text="Execution completed")

    def _display_execution_error(self, error: str):
        """Display execution error."""
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.insert(1.0, f"Execution Error:\n{error}")
        self.results_text.config(state=tk.DISABLED)
        self.execute_btn.config(state=tk.NORMAL, text="Execute Workflow")

    def _center_window(self):
        """Center the window on the parent."""
        self.update_idletasks()
        x = (
            self.parent.winfo_x()
            + (self.parent.winfo_width() // 2)
            - (self.winfo_width() // 2)
        )
        y = (
            self.parent.winfo_y()
            + (self.parent.winfo_height() // 2)
            - (self.winfo_height() // 2)
        )
        self.geometry(f"+{x}+{y}")


# Functions to integrate with existing FuzzyMatcherApp class


def add_salesforce_support_to_app(app):
    """Add Salesforce support to the existing FuzzyMatcherApp."""

    # Initialize Salesforce variables
    app.sf_integration = None
    app.sf_credentials = None
    app.sf_workflow_engine = None

    # Add to existing _init_tk_variables method
    app.sf_enabled_var = tk.BooleanVar(value=False)
    app.sf_workflow_type_var = tk.StringVar(value="dedupe")


def add_salesforce_tab_to_notebook(app, notebook):
    """Add Salesforce tab to the configuration notebook."""

    # Create Salesforce tab
    sf_tab = ttk.Frame(notebook)
    notebook.add(sf_tab, text="🔗 Salesforce")

    # Connection section
    conn_frame = ttk.LabelFrame(sf_tab, text="Salesforce Connection", padding="15")
    conn_frame.pack(fill=tk.X, padx=10, pady=10)

    # Connection status
    app.sf_status_var = tk.StringVar(value="Not connected")
    status_label = ttk.Label(conn_frame, textvariable=app.sf_status_var)
    status_label.pack(side=tk.LEFT, padx=(0, 20))

    # Connection buttons
    app.sf_connect_btn = ttk.Button(
        conn_frame,
        text="Connect to Salesforce",
        command=lambda: app._connect_to_salesforce(),  # <- NEW
    )
    app.sf_connect_btn.pack(side=tk.LEFT, padx=5)

    # Workflow section
    workflow_frame = ttk.LabelFrame(sf_tab, text="Salesforce Workflows", padding="15")
    workflow_frame.pack(fill=tk.X, padx=10, pady=10)

    ttk.Checkbutton(
        workflow_frame,
        text="Use Salesforce workflows for results processing",
        variable=app.sf_enabled_var,
    ).pack(anchor=tk.W, pady=5)

    # Workflow type selection
    type_frame = ttk.Frame(workflow_frame)
    type_frame.pack(fill=tk.X, pady=5)

    ttk.Label(type_frame, text="Workflow Type:").pack(side=tk.LEFT, padx=(20, 10))

    ttk.Radiobutton(
        type_frame,
        text="Deduplication",
        variable=app.sf_workflow_type_var,
        value="dedupe",
    ).pack(side=tk.LEFT, padx=10)

    ttk.Radiobutton(
        type_frame,
        text="Lead-to-Account Matching",
        variable=app.sf_workflow_type_var,
        value="lead_to_account",
    ).pack(side=tk.LEFT, padx=10)

    # *** ADD THIS MISSING SECTION ***
    # Data source selection frame (this was missing!)
    app.sf_data_frame = ttk.LabelFrame(
        sf_tab, text="Salesforce Data Source", padding="10"
    )
    app.sf_data_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

    # Initially show a message that connection is needed
    initial_label = ttk.Label(
        app.sf_data_frame,
        text="Connect to Salesforce to load data sources",
        font=("TkDefaultFont", 10, "italic"),
        foreground="gray",
    )
    initial_label.pack(expand=True)


def show_salesforce_connection_dialog(app):
    """Show Salesforce connection dialog."""
    dialog = SalesforceConnectionDialog(app, app.sf_credentials)
    app.wait_window(dialog)

    if dialog.result:
        app.sf_credentials = dialog.result
        app.sf_integration = SalesforceIntegration(app.sf_credentials)
        app.sf_workflow_engine = SalesforceWorkflowEngine(app.sf_integration)

        # Update status
        app.sf_status_var.set(f"✅ Connected: {dialog.result.username or 'Salesforce'}")


def add_salesforce_results_button(app, controls_frame):
    """Add Salesforce workflow button to controls."""

    # Add separator
    ttk.Separator(controls_frame, orient="vertical").pack(
        side=tk.LEFT, fill=tk.Y, padx=10
    )

    # Salesforce workflow button
    app.sf_workflow_btn = ttk.Button(
        controls_frame,
        text="🔗 Salesforce Workflow",
        command=lambda: show_salesforce_workflow_dialog(app),
        state=tk.DISABLED,
        style="Secondary.TButton",
    )
    app.sf_workflow_btn.pack(side=tk.LEFT, padx=5)


def show_salesforce_workflow_dialog(app):
    """Show Salesforce workflow dialog."""
    if not app.sf_integration or not app.sf_integration.is_connected():
        messagebox.showwarning("Not Connected", "Please connect to Salesforce first")
        return

    if app.results_df is None or app.results_df.empty:
        messagebox.showwarning(
            "No Results", "Please run matching first to generate results"
        )
        return

    workflow_type = app.sf_workflow_type_var.get()
    dialog = SalesforceWorkflowDialog(
        app, app.sf_integration, app.results_df, workflow_type
    )


def modify_refresh_ui_for_salesforce(app):
    """Modify the refresh_ui method to handle Salesforce state."""

    # This would be added to the existing refresh_ui method

    # Enable/disable Salesforce workflow button
    sf_ready = (
        hasattr(app, "sf_integration")
        and app.sf_integration
        and app.sf_integration.is_connected()
        and app.results_df is not None
        and not app.results_df.empty
    )

    if hasattr(app, "sf_workflow_btn"):
        app.sf_workflow_btn.config(state=tk.NORMAL if sf_ready else tk.DISABLED)


# Configuration management functions


def save_salesforce_config_to_session(app, session_data):
    """Save Salesforce configuration to session data."""
    if hasattr(app, "sf_credentials") and app.sf_credentials:
        # Only save non-sensitive parts
        session_data["salesforce"] = {
            "client_id": app.sf_credentials.client_id,
            "is_sandbox": app.sf_credentials.is_sandbox,
            "username": app.sf_credentials.username,
            "org_id": app.sf_credentials.org_id,
            "enabled": app.sf_enabled_var.get()
            if hasattr(app, "sf_enabled_var")
            else False,
            "workflow_type": app.sf_workflow_type_var.get()
            if hasattr(app, "sf_workflow_type_var")
            else "dedupe",
        }


def load_salesforce_config_from_session(app, session_data):
    """Load Salesforce configuration from session data."""
    if "salesforce" in session_data:
        sf_config = session_data["salesforce"]

        # Set UI variables
        if hasattr(app, "sf_enabled_var"):
            app.sf_enabled_var.set(sf_config.get("enabled", False))
        if hasattr(app, "sf_workflow_type_var"):
            app.sf_workflow_type_var.set(sf_config.get("workflow_type", "dedupe"))

        # Update status display
        if hasattr(app, "sf_status_var") and sf_config.get("username"):
            app.sf_status_var.set(f"Previous: {sf_config['username']} (disconnected)")


"""
Integration Instructions:
========================

To integrate this Salesforce functionality into your existing gui.py file:

1. Add the imports at the top of gui.py
2. In FuzzyMatcherApp.__init__(), call add_salesforce_support_to_app(self)
3. In _build_config_notebook(), call add_salesforce_tab_to_notebook(self, notebook)
4. In _build_controls_toolbar(), call add_salesforce_results_button(self, controls_frame)
5. In refresh_ui(), call modify_refresh_ui_for_salesforce(self)
6. In save_session(), call save_salesforce_config_to_session(self, session_data)
7. In load_last_session(), call load_salesforce_config_from_session(self, session_data)

Example integration in existing methods:

# In _build_config_notebook():
def _build_config_notebook(self, parent) -> ttk.Notebook:
    notebook = ttk.Notebook(parent)

    # ... existing tabs ...

    # Add Salesforce tab
    add_salesforce_tab_to_notebook(self, notebook)

    return notebook

# In refresh_ui():
def refresh_ui(self) -> None:
    # ... existing refresh logic ...

    # Add Salesforce refresh
    modify_refresh_ui_for_salesforce(self)
"""
