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_contacts(query):
    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:
        sql = """
            SELECT c.*, a.nombre as branch_name
            FROM contacts c
            JOIN accounts a ON c.location_id = a.location_id
            WHERE c.first_name LIKE ? 
               OR c.last_name LIKE ? 
               OR c.email LIKE ? 
               OR c.phone LIKE ?
            ORDER BY c.date_added DESC
        """
        q = f"%{query}%"
        rows = conn.execute(sql, (q, q, q, q)).fetchall()

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

        for idx, row in enumerate(rows, 1):
            name = f"{row['first_name'] or ''} {row['last_name'] or ''}".strip()
            phone = row['phone'] or 'N/A'
            email = row['email'] or 'N/A'
            tags = json.loads(row['tags']) if row['tags'] else []
            tags_str = ", ".join(tags) if tags else "Sin etiquetas"
            
            print(f"{idx:02d}. Nombre:     {name}")
            print(f"    Sucursal:   {row['branch_name']} ({row['location_id']})")
            print(f"    TelÃ©fono:   {phone}")
            print(f"    Email:      {email}")
            print(f"    Etiquetas:  {tags_str}")
            print(f"    Fecha GHL:  {row['date_added']}")
            print("-" * 90)
            
    finally:
        conn.close()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Error: Debes proporcionar un tÃ©rmino de bÃºsqueda.")
        print("Uso: python mp_contact_search.py <termino_de_busqueda>")
        sys.exit(1)
        
    search_query = " ".join(sys.argv[1:])
    search_contacts(search_query)
