# Multi-Layout Screenshot Troubleshooting Guide

## Issue Description
The multi-layout screenshot functionality is only capturing screenshots from the DIY module and not properly switching to the AI module. This indicates that the layout switching logic needs refinement for the current TradingView UI.

## How Multi-Layout Screenshots Work

### Current Implementation Flow
1. **Initial Screenshot**: Takes a screenshot of the current/default layout
2. **Layout Iteration**: For each layout in `config.layouts` array:
   - Calls `tradingViewAutomation.switchLayout(layout)` 
   - Calls `tradingViewAutomation.waitForLayoutLoad(layout)`
   - Takes a screenshot with layout name in filename
   - Continues to next layout

### File Naming Convention
- Default layout: `{symbol}_{timeframe}_{timestamp}_default.png`
- Specific layouts: `{symbol}_{timeframe}_{layout}_{timestamp}.png`

## Debugging Layout Switching Issues

### Step 1: Enable Debug Logging
The switchLayout method already includes extensive logging. Look for these messages:

```
🎛️ Switching to {layout} layout...
🎯 Found {layout} layout element: {selector} with text: {text}
✅ Successfully switched to {layout} layout
⚠️ Could not find {layout} layout switcher
```

### Step 2: Inspect Browser Console
When running the application, check the browser console for:
- Layout switching attempts
- Element detection results
- Any JavaScript errors during layout switching

### Step 3: Manual TradingView Inspection
To find the correct selectors for AI and DIY modules:

1. Open TradingView in a browser
2. Log in and navigate to a chart
3. Look for AI and DIY module buttons/tabs
4. Right-click and "Inspect Element"
5. Note the actual HTML structure and attributes

### Common Selectors to Check
Look for elements with these characteristics:
- `data-name` attributes containing "ai", "diy", "module", or "layout"
- `class` names with "ai", "diy", "module", "tab", or "button"
- `title` or `aria-label` attributes mentioning AI or DIY
- Button elements in the top toolbar or side panels

## Updating Selectors for Current TradingView UI

### Current Selectors in switchLayout Method
The method searches for these selector patterns:
```typescript
const layoutSwitcherSelectors = [
  // Top toolbar layout buttons
  '[data-name="chart-layout"]',
  '[data-name="layout-switcher"]',
  '.tv-layout-switcher',
  '.chart-layout-switcher',
  
  // Module/layout tabs
  '[data-name="module-switcher"]',
  '.module-switcher',
  '.tv-module-tabs',
  '.tv-chart-tabs',
  
  // Modern TradingView UI selectors
  '[data-testid*="layout"]',
  '[data-testid*="module"]',
  '[data-testid*="ai"]',
  '[data-testid*="diy"]',
  
  // Header/toolbar buttons
  '.tv-header__button',
  '.tv-toolbar__button',
  '.tv-chart-header__button',
  
  // Generic interactive elements
  '[role="tab"]',
  '[role="button"]',
  'button',
  '.tv-button',
  
  // Specific content-based selectors
  '[title*="AI"]',
  '[title*="DIY"]',
  '[aria-label*="AI"]',
  '[aria-label*="DIY"]',
  '[data-tooltip*="AI"]',
  '[data-tooltip*="DIY"]',
  
  // Menu items
  '.tv-dropdown-behavior__item',
  '.tv-menu__item',
  '.tv-context-menu__item'
]
```

### How to Add New Selectors
If you find different selectors through inspection:

1. Edit `/lib/tradingview-automation.ts`
2. Find the `switchLayout` method
3. Add new selectors to the `layoutSwitcherSelectors` array
4. Test the updated implementation

Example of adding a new selector:
```typescript
const layoutSwitcherSelectors = [
  // ... existing selectors ...
  
  // Add your new selectors here
  '[data-module-name="ai-analysis"]',
  '[data-module-name="diy-builder"]',
  '.chart-module-ai',
  '.chart-module-diy'
]
```

## Testing Multi-Layout Functionality

### Method 1: Using API Endpoints
```bash
# Update settings to include both layouts
curl -X POST http://localhost:3000/api/settings \
  -H "Content-Type: application/json" \
  -d '{"symbol": "SOLUSD", "timeframe": "240", "layouts": ["ai", "diy"]}'

# Trigger analysis with multiple layouts  
curl -X POST http://localhost:3000/api/analyze \
  -H "Content-Type: application/json" \
  -d '{"symbol": "SOLUSD", "timeframe": "240", "layouts": ["ai", "diy"], "useExisting": false}'
```

### Method 2: Using Test Scripts
```bash
# Run the multi-layout API test
node test-multi-layout-api.js
```

### Method 3: Dashboard Interface
1. Open the dashboard at http://localhost:3000
2. Go to Developer Settings
3. Set layouts to include both "ai" and "diy"
4. Trigger an analysis
5. Check the screenshots directory for multiple files

## Expected Results

### Successful Multi-Layout Capture
You should see multiple screenshot files:
```
screenshots/
├── SOLUSD_240_1234567890_default.png
├── SOLUSD_240_ai_1234567890.png
└── SOLUSD_240_diy_1234567890.png
```

### API Response
The API should return:
```json
{
  "screenshots": [
    "SOLUSD_240_1234567890_default.png",
    "SOLUSD_240_ai_1234567890.png", 
    "SOLUSD_240_diy_1234567890.png"
  ],
  "layoutsAnalyzed": ["ai", "diy"]
}
```

## Common Issues and Solutions

### Issue: Only DIY Screenshots Captured
**Cause**: AI module selector not found or layout switching failed  
**Solution**: 
1. Check if AI module is visible/enabled in TradingView
2. Inspect and update AI module selectors
3. Verify AI module is available for your TradingView account

### Issue: No Layout Switching Occurs
**Cause**: All layout selectors are outdated  
**Solution**:
1. Inspect current TradingView UI structure
2. Update selectors in switchLayout method
3. Add fallback keyboard shortcuts

### Issue: Screenshots Identical Despite Layout Names
**Cause**: Layout switching appears successful but UI doesn't actually change  
**Solution**:
1. Increase wait time in waitForLayoutLoad method
2. Add visual verification that layout actually changed
3. Check if modules need to be manually enabled in TradingView

## Advanced Debugging

### Enable Verbose Layout Detection
Add this to the beginning of `switchLayout` method for more detailed logging:

```typescript
// Take debug screenshot before switching
await this.takeDebugScreenshot(`before_switch_to_${layoutType}`)

// Log all visible buttons/tabs for debugging
const allButtons = await this.page.locator('button, [role="button"], [role="tab"]').all()
for (const button of allButtons) {
  const text = await button.textContent().catch(() => '')
  const title = await button.getAttribute('title').catch(() => '')
  if (text || title) {
    console.log(`🔍 Found button/tab: "${text}" title: "${title}"`)
  }
}
```

### Visual Layout Verification
Add visual verification after layout switching:

```typescript
// After successful layout switch, verify visually
const layoutElements = await this.page.locator('[class*="ai"], [class*="diy"], [data-name*="ai"], [data-name*="diy"]').all()
console.log(`📊 Found ${layoutElements.length} layout-specific elements after switch`)
```

## Next Steps

1. **Run the test scripts** to see current behavior
2. **Check browser console logs** for layout switching attempts
3. **Inspect TradingView UI** to find correct selectors
4. **Update selectors** in the switchLayout method if needed
5. **Test again** to verify multi-layout functionality

The multi-layout framework is already in place and working correctly. The issue is likely just selector specificity for the current TradingView UI structure.
