# -*- coding: utf-8 -*-
import json
import ovh
import os
import sys
import psycopg2

# DB Config
DB_PARAMS = {
    "host": "localhost",
    "database": "smarteye",
    "user": "lucas",
    "password": "smarteye_db_pass"
}

# --- CONFIGURATION OVH (A REMPLIR AVEC TES VRAIES CLES) ---
client = ovh.Client(
    endpoint='ovh-eu',
    application_key='dc809738a0e0ca05',
    application_secret='9a0b1723318676047919f397cabbd4d6',
    consumer_key='f1cd0f7101fe2f9e57d1e3bc7c230fa0'
)
SERVICE_NAME = "sms-gr31483-1"  # Ton ID Service (gardé de ton ancien code)

# --- MAIN : Réception des ordres de PHP ---
if __name__ == "__main__":
    # On attend 2 arguments : le numéro et le message
    if len(sys.argv) < 3:
        print("Erreur: Arguments manquants")
        sys.exit(1)

    destinataire = sys.argv[1]
    message_txt = sys.argv[2]

    try:
        # ENVOI REEL OVH
        result = client.post(f'/sms/{SERVICE_NAME}/jobs',
            message=message_txt,
            sender="UNIGESTFR",      
            receivers=[destinataire],
            noStopClause=True,
            priority="high"
        )
        print(f"✅ SUCCÈS OVH: {result}")

    except Exception as e:
        print(f"❌ ERREUR OVH: {str(e)}")



def get_contacts(client_id):
    """Lit database.json et renvoie le Nom du client et la liste des numéros"""
    db_path = '/var/www/lucas/database.json' # Chemin absolu pour être sûr
    
    if not os.path.exists(db_path):
        return "Inconnu", []

    try:
        with open(db_path, 'r') as f:
            data = json.load(f)
            
        # Structure : clients -> client_id -> contacts
        client_data = data.get("clients", {}).get(client_id)
        if not client_data:
            return "Client Inconnu", []

        nom_client = client_data.get("name", "Client")
        contacts_list = client_data.get("contacts", [])
        
        numeros_a_contacter = []
        for contact in contacts_list:
            phone = contact.get("phone")
            if phone:
                # Nettoyage
                clean = phone.replace(" ", "").replace(".", "").replace("-", "")
                numeros_a_contacter.append(clean)
                
        return nom_client, numeros_a_contacter

    except Exception as e:
        sys.stderr.write(f"Erreur lecture DB: {e}\n")
        return "Erreur", []

def send_alert(client_id, image_url=""):
    """Envoie le SMS à tous les contacts du client"""
    nom_client, numeros = get_contacts(client_id)
    
    if not numeros:
        return False, "Aucun contact trouvé"

    message_txt = f"ALERTE CHUTE ! {nom_client} est au sol. Voir preuve : {image_url}"
    
    # On tronque si trop long (sécurité)
    if len(message_txt) > 160: message_txt = message_txt[:160]

    logs = []
    for num in numeros:
        try:
            # ENVOI REEL OVH
            result = client.post(f'/sms/{SERVICE_NAME}/jobs',
                message=message_txt,
                sender="UNIGESTFR",      # <--- ON AJOUTE TON SENDER ICI
                senderForResponse=False, # <--- ON MET FALSE (Impossible de répondre à un nom)
                receivers=[num],
                noStopClause=True,
                priority="high"
            )
            )
            logs.append(f"OK vers {num}")
            
            # --- LOG TO POSTGRES ---
            try:
                conn = psycopg2.connect(**DB_PARAMS)
                cur = conn.cursor()
                cur.execute("""
                    INSERT INTO sms_logs (to_number, client_name, message, status, provider_id)
                    VALUES (%s, %s, %s, %s, %s)
                """, (num, nom_client, message_txt, "SENT", str(result.get('ids', [''])[0])))
                conn.commit()
                cur.close()
                conn.close()
            except Exception as e:
                logs.append(f"DB ERROR: {e}")
                
        except Exception as e:
            logs.append(f"ECHEC vers {num}: {str(e)}")
            # Log failure to DB too
            try:
                conn = psycopg2.connect(**DB_PARAMS)
                cur = conn.cursor()
                cur.execute("""
                    INSERT INTO sms_logs (to_number, client_name, message, status)
                    VALUES (%s, %s, %s, %s)
                """, (num, nom_client, message_txt, "ERROR"))
                conn.commit()
                cur.close()
                conn.close()
            except: pass
            
    return True, ", ".join(logs)
