""" CropDrive Website Integration Module Handles communication with parent window when embedded in CropDrive website This module implements the AI Assistant Integration Guide specification for sending ANALYSIS_COMPLETE messages to the parent window. The message format matches the exact specification in the integration guide. Key Functions: - send_analysis_complete(): Sends analysis completion message (matches guide format) - send_error_message(): Sends error message when analysis fails - initialize_integration(): Initializes integration and gets user config """ import streamlit as st from utils.streamlit_runtime import embed_html as html import json import logging # Configure logger logger = logging.getLogger(__name__) # ============================================================================ # STEP 1: JavaScript for parent window communication # ============================================================================ def inject_parent_communication(): """Inject JavaScript to communicate with parent window (CropDrive website)""" js_code = """ """ html(js_code, height=0) # ============================================================================ # STEP 2: Initialize integration and get language # ============================================================================ def initialize_integration(): """Initialize integration and get current language""" # Inject communication JavaScript inject_parent_communication() # Get language from URL parameters (always check on each run) query_params = st.query_params current_lang = query_params.get('lang', 'en') # Validate language if current_lang not in ['en', 'ms', 'id']: current_lang = 'en' # Always update language from URL params (handles dynamic changes) st.session_state.language = current_lang # Get user config from URL user_id = query_params.get('userId', '') user_email = query_params.get('userEmail', '') user_name = query_params.get('userName', '') user_plan = query_params.get('plan', 'none') features_str = query_params.get('features', '') features = features_str.split(',') if features_str else [] # Get upload limits from URL parameters uploads_used = query_params.get('uploadsUsed', '0') uploads_limit = query_params.get('uploadsLimit', '0') upload_limit_exceeded = query_params.get('uploadLimitExceeded', 'false') uploads_remaining_param = query_params.get('uploadsRemaining', '') # Convert to appropriate types try: uploads_used = int(uploads_used) if uploads_used else 0 except (ValueError, TypeError): uploads_used = 0 try: uploads_limit = int(uploads_limit) if uploads_limit else 0 except (ValueError, TypeError): uploads_limit = 0 try: upload_limit_exceeded = upload_limit_exceeded.lower() == 'true' if upload_limit_exceeded else False except (AttributeError, ValueError): upload_limit_exceeded = False # Calculate uploads_remaining ourselves: limit - used # This ensures correct calculation regardless of what parent sends if uploads_limit == 0 or uploads_limit == -1: # No limit or unlimited plan uploads_remaining = float('inf') else: # Calculate remaining: limit - used uploads_remaining = max(0, uploads_limit - uploads_used) # Override with parent's value only if it indicates unlimited (-1 or infinity) if uploads_remaining_param: try: uploads_remaining_str = str(uploads_remaining_param).lower() if uploads_remaining_str == 'infinity' or uploads_remaining_str == '-1' or uploads_remaining_str == 'inf': uploads_remaining = float('inf') except (ValueError, TypeError): pass # Use our calculated value # Store user config in session state if 'user_config' not in st.session_state: st.session_state.user_config = { 'userId': user_id, 'plan': user_plan, 'features': features } # Also store user info in session state for Firebase storage (for backward compatibility) if user_id: st.session_state.user_id = user_id if user_email: st.session_state.user_email = user_email if user_name: st.session_state.user_name = user_name # Update user_config with email and name st.session_state.user_config['userEmail'] = user_email st.session_state.user_config['userName'] = user_name # Store upload limits in session state # CRITICAL: Always update from URL params to get latest values (parent may have updated them) # This ensures upload counts stay in sync with parent website st.session_state.uploads_used = uploads_used st.session_state.uploads_limit = uploads_limit st.session_state.upload_limit_exceeded = upload_limit_exceeded st.session_state.uploads_remaining = uploads_remaining # Log upload count for debugging logger.info(f"📊 Upload count from URL: {uploads_used}/{uploads_limit} used ({uploads_remaining} remaining)") return current_lang, user_plan, features # ============================================================================ # STEP 3: Send analysis results to website # ============================================================================ def request_config_update(): """ Request updated CONFIG from parent window after analysis This should be called after analysis completes to get updated upload counts """ from utils.streamlit_runtime import embed_html as html import json request_js = f""" """ html(request_js, height=0) # ============================================================================ # STEP 3: Send analysis results to website # ============================================================================ def send_analysis_complete( title: str, analysis_type: str, # 'soil' or 'leaf' summary: str = '', recommendations_count: int = 0, file_url: str = None, analysis_data: dict = None ): """ CRITICAL: Send analysis completion message to parent window (CropDrive website) This message MUST be sent after every analysis completes to save results to Firestore. This function implements the exact message format specified in the AI Assistant Integration Guide. The website automatically uses the authenticated user's ID, so userId is NOT included in the message. Args: title: Report title (required) - e.g., "Analysis Report - 2024-01-15" analysis_type: 'soil' or 'leaf' (required) summary: Analysis summary text (required) - Brief summary of the analysis recommendations_count: Number of recommendations (required) - Number of recommendations generated file_url: URL to the uploaded file (optional) analysis_data: Full analysis data object (optional) - Can contain any structure """ from datetime import datetime try: # Get user ID for logging purposes only (not sent in message per guide specification) user_id = get_user_id() user_email = get_user_email() # Log user info for debugging logger.info(f"🔍 DEBUG send_analysis_complete - user_id: {user_id}, user_email: {user_email}") # Ensure analysis_data includes timestamp if not already present if analysis_data is None: analysis_data = {} # Add timestamp if not already in analysis_data if 'timestamp' not in analysis_data: analysis_data['timestamp'] = datetime.now().isoformat() # CRITICAL: Build message with exact format specified in the integration guide # NOTE: userId is NOT included per guide specification - website uses authenticated user's ID message = { 'type': 'ANALYSIS_COMPLETE', # MUST be exactly this string 'title': title or f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}', 'analysisType': analysis_type or 'soil', # 'soil' or 'leaf' 'summary': summary or '', # Required: Brief summary of the analysis 'recommendationsCount': int(recommendations_count) if recommendations_count else 0, # Required: Number of recommendations 'fileUrl': file_url or None, # Optional: URL to the uploaded file 'analysisData': analysis_data or {} # Optional: Full analysis data object } # Log the complete message for debugging # Note: sessionStorage is handled in JavaScript code below logger.info(f"📤 Sending ANALYSIS_COMPLETE message: title={title}, type={analysis_type}") logger.info(f"📤 Message payload: {json.dumps(message, indent=2)}") # CRITICAL: Use '*' as target origin to avoid origin mismatch errors # The parent page will verify the message origin on its side send_js = f""" """ # Inject the JavaScript html(send_js, height=0) # Also log in Python logger.info(f"✅ ANALYSIS_COMPLETE message HTML injected") # Show success message to user st.success("✅ Analysis completed! Results are being saved...") except Exception as e: # CRITICAL: Log error but don't fail silently logger.error(f"❌ CRITICAL ERROR in send_analysis_complete: {e}") import traceback logger.error(f"❌ Traceback: {traceback.format_exc()}") # Try to send a minimal message even if there's an error try: minimal_message = { 'type': 'ANALYSIS_COMPLETE', 'title': title or f'Analysis Report - {datetime.now().strftime("%Y-%m-%d")}', 'analysisType': analysis_type or 'soil', 'summary': summary or 'Analysis completed successfully.', 'recommendationsCount': 0, 'fileUrl': None, 'analysisData': {} } fallback_js = f""" """ html(fallback_js, height=0) except Exception as fallback_error: logger.error(f"❌ Failed to send fallback ANALYSIS_COMPLETE message: {fallback_error}") # ============================================================================ # STEP 4: Handle plan-based features # ============================================================================ def is_feature_available(feature_name: str, user_plan: str) -> bool: """ Check if a feature is available for the user's plan Args: feature_name: Name of the feature ('basic', 'priority', 'premium', 'comparative', 'early_access') user_plan: User's plan ('start', 'smart', 'precision', 'none') Returns: True if feature is available, False otherwise """ plan_features = { 'start': ['basic'], 'smart': ['basic', 'priority'], 'precision': ['basic', 'priority', 'premium', 'comparative', 'early_access'], 'none': [] # No features for unsubscribed users } available_features = plan_features.get(user_plan, ['basic']) return feature_name in available_features def send_feature_restricted(required_plan: str, feature_name: str): """ Notify parent window that user tried to use a restricted feature Args: required_plan: Plan required to access the feature feature_name: Name of the restricted feature """ message = { 'type': 'FEATURE_RESTRICTED', 'requiredPlan': required_plan, 'featureName': feature_name } # IMPORTANT: Use '*' as target origin to avoid origin mismatch errors # The parent page will verify the message origin on its side send_js = f""" """ html(send_js, height=0) def get_user_plan(): """Get current user plan from session state""" return st.session_state.get('user_config', {}).get('plan', 'none') def get_user_id(): """Get current user ID from session state""" # Try multiple sources for user ID user_id = st.session_state.get('user_id', '') if not user_id: user_id = st.session_state.get('user_config', {}).get('userId', '') return user_id def get_user_email(): """Get current user email from session state""" user_email = st.session_state.get('user_email', '') if not user_email: user_email = st.session_state.get('user_config', {}).get('userEmail', '') return user_email def get_user_name(): """Get current user name from session state""" user_name = st.session_state.get('user_name', '') if not user_name: user_name = st.session_state.get('user_config', {}).get('userName', '') return user_name def can_start_analysis(): """ Check if user can start a new analysis based on upload limits Returns: True if analysis can start, False otherwise """ # Get current values uploads_used = st.session_state.get('uploads_used', 0) uploads_limit = st.session_state.get('uploads_limit', 0) upload_limit_exceeded = st.session_state.get('upload_limit_exceeded', False) uploads_remaining = st.session_state.get('uploads_remaining', 0) # Ensure values are numeric try: uploads_used = int(uploads_used) if uploads_used is not None else 0 uploads_limit = int(uploads_limit) if uploads_limit is not None else 0 except (ValueError, TypeError): uploads_used = 0 uploads_limit = 0 logger.info(f"🔍 can_start_analysis check: used={uploads_used}, limit={uploads_limit}, exceeded={upload_limit_exceeded}, remaining={uploads_remaining}") # If upload_limit_exceeded flag is set, block analysis if upload_limit_exceeded: logger.info("❌ Analysis blocked: upload_limit_exceeded flag is True") return False # If no limit set (0 or -1), allow unlimited analyses if uploads_limit == 0 or uploads_limit == -1: logger.info("✅ Analysis allowed: no limit set (unlimited)") return True # Recalculate remaining to ensure accuracy: limit - used calculated_remaining = max(0, uploads_limit - uploads_used) # If calculated remaining is infinity, allow if calculated_remaining == float('inf'): logger.info("✅ Analysis allowed: unlimited remaining") return True # If calculated remaining is greater than 0, allow analysis if calculated_remaining > 0: logger.info(f"✅ Analysis allowed: {calculated_remaining} remaining") return True # Otherwise, block (remaining is 0 or less) logger.info(f"❌ Analysis blocked: {calculated_remaining} remaining (limit reached)") return False def get_upload_limit_info(): """ Get upload limit information for display Returns: Dictionary with upload limit information """ uploads_used = st.session_state.get('uploads_used', 0) uploads_limit = st.session_state.get('uploads_limit', 0) upload_limit_exceeded = st.session_state.get('upload_limit_exceeded', False) # Calculate remaining: limit - used (ensure accuracy) if uploads_limit == 0 or uploads_limit == -1: uploads_remaining = float('inf') else: uploads_remaining = max(0, uploads_limit - uploads_used) return { 'uploads_used': uploads_used, 'uploads_limit': uploads_limit, 'upload_limit_exceeded': upload_limit_exceeded, 'uploads_remaining': uploads_remaining } def send_script_run_state_changed(script_run_state: str, progress: int = None, message: str = None) -> None: """ Send analysis progress/status update to parent window This is useful for showing progress bars and status messages during long-running analyses Args: script_run_state: 'running' or 'notRunning' progress: Optional progress percentage (0-100) message: Optional status message """ message_data = { 'type': 'SCRIPT_RUN_STATE_CHANGED', 'scriptRunState': script_run_state } if progress is not None: message_data['progress'] = progress if message is not None: message_data['message'] = message # IMPORTANT: Use '*' as target origin to avoid origin mismatch errors # The parent page will verify the message origin on its side send_js = f""" """ html(send_js, height=0) def send_language_change(new_language: str): """Send language change notification to parent window when language changes within Streamlit""" # Validate language if new_language not in ['en', 'ms', 'id']: new_language = 'en' # Update session state st.session_state.language = new_language # Update URL parameter query_params = st.query_params query_params['lang'] = new_language # Send message to parent window message = { 'type': 'LANGUAGE_CHANGE_REQUEST', 'language': new_language } # IMPORTANT: Use '*' as target origin to avoid origin mismatch errors # The parent page will verify the message origin on its side send_js = f""" """ html(send_js, height=0) # Trigger rerun to apply language change st.rerun() # ============================================================================ # STEP 5: Additional Message Types # ============================================================================ def send_error_message(error_message: str, details: str = None) -> None: """ Send error message to parent window when analysis fails. Matches the format specified in the AI Assistant Integration Guide. Args: error_message: Error message to display (required) details: Additional error details (optional) """ from utils.streamlit_runtime import embed_html as html import json error_data = { 'type': 'ANALYSIS_ERROR', 'error': error_message, } if details: error_data['details'] = details send_js = f""" """ html(send_js, height=0) def send_progress_update(current_step: int, total_steps: int, status_message: str = None) -> None: """ Send progress update during analysis Args: current_step: Current step number total_steps: Total number of steps status_message: Optional status message """ progress = int((current_step / total_steps) * 100) message = status_message or f"Processing step {current_step} of {total_steps}" send_script_run_state_changed( script_run_state='running', progress=progress, message=message ) # ============================================================================ # STEP 6: Safe postMessage utility # ============================================================================ def safe_post_message(message, target_origin='*'): """ Safely send postMessage with comprehensive error handling Args: message: Message object to send target_origin: Target origin for postMessage ('*' by default) """ from utils.streamlit_runtime import embed_html as html import json safe_js = f""" """ html(safe_js, height=0)