import os
import sys
import sqlite3
import json

# Ruta a la base de datos (un nivel arriba del script)
import sys as _sys, os as _os
_sys.path.insert(0, _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))))
from paths import DB_PATH as DB_PATH
def search_opportunities(query_or_status):
    if not os.path.exists(DB_PATH):
        print(f"Error: La base de datos local no existe en {DB_PATH}.")
        print("Por favor, ejecuta la sincronizaciÃ³n global primero desde el dashboard.")
        sys.exit(1)

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    
    try:
        # Si es un estado
        status_clean = query_or_status.lower().strip()
        is_status_query = status_clean in ("open", "won", "lost", "abandoned")

        if is_status_query:
            sql = """
                SELECT o.*, a.nombre as branch_name, c.first_name, c.last_name, c.phone, c.email
                FROM opportunities o
                JOIN accounts a ON o.location_id = a.location_id
                LEFT JOIN contacts c ON o.contact_id = c.id AND o.location_id = c.location_id
                WHERE o.status = ?
                ORDER BY o.date_added DESC
            """
            rows = conn.execute(sql, (status_clean,)).fetchall()
        else:
            sql = """
                SELECT o.*, a.nombre as branch_name, c.first_name, c.last_name, c.phone, c.email
                FROM opportunities o
                JOIN accounts a ON o.location_id = a.location_id
                LEFT JOIN contacts c ON o.contact_id = c.id AND o.location_id = c.location_id
                WHERE o.name LIKE ? 
                   OR c.first_name LIKE ? 
                   OR c.last_name LIKE ?
                ORDER BY o.date_added DESC
            """
            q = f"%{query_or_status}%"
            rows = conn.execute(sql, (q, q, q)).fetchall()

        print(f"=== BÃšSQUEDA GLOBAL DE OPORTUNIDADES ===")
        print(f"Criterio de bÃºsqueda: '{query_or_status}'")
        print(f"Resultados encontrados: {len(rows)}\n")
        print("-" * 100)
        
        if not rows:
            print("No se encontraron oportunidades que coincidan con la bÃºsqueda.")
            return

        for idx, row in enumerate(rows, 1):
            contact_name = f"{row['first_name'] or ''} {row['last_name'] or ''}".strip()
            if not contact_name:
                contact_name = "Sin contacto asociado"
                
            opp_name = row['name'] or 'Sin nombre'
            status = row['status'].upper() if row['status'] else 'OPEN'
            val = row['monetary_value'] or 0.0
            
            # Formatear valor como moneda
            val_formatted = f"${val:,.2f}"

            print(f"{idx:02d}. Oportunidad: {opp_name}")
            print(f"    Sucursal:     {row['branch_name']}")
            print(f"    Cliente:      {contact_name}")
            print(f"    Estado:       {status}")
            print(f"    Valor:        {val_formatted}")
            print(f"    Fecha GHL:    {row['date_added']}")
            print("-" * 100)
            
    finally:
        conn.close()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Error: Debes proporcionar un tÃ©rmino de bÃºsqueda o estado (open/won/lost/abandoned).")
        print("Uso: python mp_opportunity_search.py <criterio_o_status>")
        sys.exit(1)
        
    search_query = " ".join(sys.argv[1:])
    search_opportunities(search_query)
