"""
SIMPLIFIED DIAGNOSTIC APP - Verify raw data first
Shows raw totals with NO filters to verify data is being read correctly
"""

from flask import Flask, jsonify, session, render_template_string
from flask_login import LoginManager, login_required, current_user
import gspread
from google.oauth2.credentials import Credentials
import pandas as pd
import sys

# Import from main app
sys.path.insert(0, '.')
from app import (
    app, login_manager, users, get_google_credentials, 
    find_column, parse_currency
)

@app.route('/diagnostic')
@login_required
def diagnostic():
    """Diagnostic page to verify raw data."""
    creds = get_google_credentials()
    if not creds:
        return "Not authenticated", 401
    
    try:
        SPREADSHEET_ID = session.get('spreadsheet_id')
        if not SPREADSHEET_ID:
            return "Spreadsheet ID not configured", 400
        
        # Fetch raw data
        gc = gspread.authorize(creds)
        spreadsheet = gc.open_by_key(SPREADSHEET_ID)
        
        # List all worksheets
        all_worksheets = spreadsheet.worksheets()
        sheets_info = []
        
        for idx, ws in enumerate(all_worksheets):
            sheets_info.append(f"[{idx}] {ws.title} ({ws.row_count} rows x {ws.col_count} cols)")
        
        # Read from second sheet (index 1)
        worksheet = spreadsheet.worksheets()[1]
        all_values = worksheet.get_all_values()
        
        if not all_values:
            return "No data in sheet", 400
        
        headers = all_values[0]
        data = all_values[1:]
        df = pd.DataFrame(data, columns=headers)
        df.columns = df.columns.str.strip()
        
        # Find columns
        mes_col = find_column(df, 'mes')
        fat_col = find_column(df, 'faturacao')
        quant_col = find_column(df, 'quantidade')
        cliente_col = find_column(df, 'cliente')
        
        # Show RAW samples BEFORE parsing
        raw_samples = []
        if fat_col:
            raw_samples = df[fat_col].head(20).tolist()
        
        # Parse faturacao column
        if fat_col:
            df[fat_col] = df[fat_col].apply(parse_currency)
        if quant_col:
            df[quant_col] = df[quant_col].apply(parse_currency)
        
        # Calculate RAW totals (no filters)
        total_rows = len(df)
        total_fat_raw = df[fat_col].sum() if fat_col else 0
        total_quant_raw = df[quant_col].sum() if quant_col else 0
        unique_clients_raw = df[cliente_col].nunique() if cliente_col else 0
        
        # Calculate totals by year
        year_totals = {}
        if mes_col and fat_col:
            for year in ['2024', '2025', '2026']:
                year_df = df[df[mes_col].astype(str).str.contains(year, na=False, regex=False)]
                year_totals[year] = {
                    'rows': len(year_df),
                    'faturacao': year_df[fat_col].sum(),
                    'quantidade': year_df[quant_col].sum() if quant_col else 0,
                    'clientes': year_df[cliente_col].nunique() if cliente_col else 0
                }
        
        # Sample dates
        sample_dates = df[mes_col].head(20).tolist() if mes_col else []
        
        # Build HTML response
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>Data Diagnostic</title>
            <style>
                body {{ font-family: monospace; padding: 20px; background: #1a1a1a; color: #0f0; }}
                h1, h2 {{ color: #0ff; }}
                .section {{ background: #2a2a2a; padding: 15px; margin: 15px 0; border-left: 4px solid #0f0; }}
                .error {{ color: #f00; }}
                .success {{ color: #0f0; }}
                .warning {{ color: #ff0; }}
                table {{ border-collapse: collapse; width: 100%; margin: 10px 0; }}
                th, td {{ border: 1px solid #0f0; padding: 8px; text-align: left; }}
                th {{ background: #0f0; color: #000; }}
                .raw {{ color: #aaa; font-size: 0.9em; }}
            </style>
        </head>
        <body>
            <h1>📊 DATA DIAGNOSTIC REPORT</h1>
            
            <div class="section">
                <h2>📁 Spreadsheet Information</h2>
                <p><strong>Spreadsheet ID:</strong> {SPREADSHEET_ID}</p>
                <p><strong>Total Worksheets:</strong> {len(all_worksheets)}</p>
                <ul>
                    {''.join(f'<li>{info}</li>' for info in sheets_info)}
                </ul>
                <p class="warning">⚠️ App is reading from: [{1}] {worksheet.title}</p>
            </div>
            
            <div class="section">
                <h2>📋 Columns Found</h2>
                <p><strong>All Columns:</strong> {', '.join(df.columns.tolist())}</p>
                <p><strong>Mês Column:</strong> {mes_col or 'NOT FOUND'}</p>
                <p><strong>Faturação Column:</strong> {fat_col or 'NOT FOUND'}</p>
                <p><strong>Quantidade Column:</strong> {quant_col or 'NOT FOUND'}</p>
                <p><strong>Cliente Column:</strong> {cliente_col or 'NOT FOUND'}</p>
            </div>
            
            <div class="section">
                <h2>🔍 RAW Data Samples (BEFORE Parsing)</h2>
                <p class="raw">First 20 values from Faturação column:</p>
                <ul class="raw">
                    {''.join(f'<li>{val}</li>' for val in raw_samples)}
                </ul>
            </div>
            
            <div class="section">
                <h2>📅 Date Samples</h2>
                <p>First 20 dates from Mês column:</p>
                <ul>
                    {''.join(f'<li>{date}</li>' for date in sample_dates)}
                </ul>
            </div>
            
            <div class="section">
                <h2>💰 RAW TOTALS (NO FILTERS)</h2>
                <table>
                    <tr>
                        <th>Metric</th>
                        <th>Value</th>
                    </tr>
                    <tr>
                        <td>Total Rows</td>
                        <td class="success">{total_rows:,}</td>
                    </tr>
                    <tr>
                        <td>Total Faturação</td>
                        <td class="success">€ {total_fat_raw:,.2f}</td>
                    </tr>
                    <tr>
                        <td>Total Quantidade</td>
                        <td class="success">{total_quant_raw:,.0f}</td>
                    </tr>
                    <tr>
                        <td>Unique Clientes</td>
                        <td class="success">{unique_clients_raw:,}</td>
                    </tr>
                </table>
            </div>
            
            <div class="section">
                <h2>📊 TOTALS BY YEAR</h2>
                <table>
                    <tr>
                        <th>Year</th>
                        <th>Rows</th>
                        <th>Faturação</th>
                        <th>Quantidade</th>
                        <th>Clientes</th>
                    </tr>
                    {''.join(f'''
                    <tr>
                        <td>{year}</td>
                        <td>{data["rows"]:,}</td>
                        <td class="{"success" if year == "2025" else ""}">€ {data["faturacao"]:,.2f}</td>
                        <td>{data["quantidade"]:,.0f}</td>
                        <td>{data["clientes"]:,}</td>
                    </tr>
                    ''' for year, data in year_totals.items())}
                </table>
            </div>
            
            <div class="section">
                <h2>✅ Comparison with Looker Studio (Year 2025)</h2>
                <table>
                    <tr>
                        <th>Source</th>
                        <th>Faturação</th>
                        <th>Status</th>
                    </tr>
                    <tr>
                        <td>Looker Studio (Expected)</td>
                        <td>€ 6,005,182.69</td>
                        <td class="success">✓ Reference</td>
                    </tr>
                    <tr>
                        <td>This App (Current)</td>
                        <td>€ {year_totals.get('2025', {}).get('faturacao', 0):,.2f}</td>
                        <td class="{"success" if abs(year_totals.get('2025', {}).get('faturacao', 0) - 6005182.69) < 1 else "error"}">
                            {"✓ MATCH!" if abs(year_totals.get('2025', {}).get('faturacao', 0) - 6005182.69) < 1 else "✗ MISMATCH"}
                        </td>
                    </tr>
                </table>
            </div>
            
            <p><a href="/dashboard" style="color: #0ff;">← Back to Dashboard</a></p>
        </body>
        </html>
        """
        
        return html
        
    except Exception as e:
        return f"<pre style='color:red'>ERROR: {str(e)}\n\nImport traceback:\n{__import__('traceback').format_exc()}</pre>", 500


if __name__ == '__main__':
    print("Navigate to: http://localhost:5000/diagnostic")
    print("This will show raw data totals to verify the issue")
