#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
====================================================================
🐯 TigrouToBombrito - Discord Rich Presence pour Compte Classique
====================================================================
Ce script se connecte automatiquement à votre application Discord
ouverte sur votre PC (Windows / Mac / Linux) et affiche votre activité
Minecraft avec les informations en direct du serveur TigrouToBombrito !

100% SÉCURISÉ : Aucun mot de passe ni token Discord requis.
====================================================================
"""
import os
import sys
import json
import time
import struct
import socket
import urllib.request

CLIENT_ID = "1551282825234223234"
PANEL_URL = "https://tigroutobombrito.tigrou.online/api/discord/rpc/client-sync"

class DiscordIPC:
    def __init__(self, client_id):
        self.client_id = client_id
        self.pipe = None
        self.is_windows = sys.platform == 'win32'

    def connect(self):
        if self.is_windows:
            for i in range(10):
                path = rf'\.\pipe\discord-ipc-{i}'
                try:
                    self.pipe = open(path, 'r+b', buffering=0)
                    self._handshake()
                    return True
                except Exception:
                    continue
        else:
            candidates = [
                os.environ.get('TMPDIR', ''),
                os.environ.get('XDG_RUNTIME_DIR', ''),
                os.environ.get('TMP', ''),
                os.environ.get('TEMP', ''),
                '/tmp'
            ]
            for folder in candidates:
                if not folder or not os.path.isdir(folder):
                    continue
                for i in range(10):
                    path = os.path.join(folder, f'discord-ipc-{i}')
                    if os.path.exists(path):
                        try:
                            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                            s.connect(path)
                            self.pipe = s
                            self._handshake()
                            return True
                        except Exception:
                            continue
        return False

    def _send(self, op, payload):
        data = json.dumps(payload).encode('utf-8')
        header = struct.pack('<II', op, len(data))
        if self.is_windows:
            self.pipe.write(header + data)
        else:
            self.pipe.sendall(header + data)

    def _recv(self):
        try:
            if self.is_windows:
                header = self.pipe.read(8)
                if not header or len(header) < 8: return None, None
                op, length = struct.unpack('<II', header)
                data = self.pipe.read(length)
                return op, json.loads(data.decode('utf-8'))
            else:
                header = self.pipe.recv(8)
                if not header or len(header) < 8: return None, None
                op, length = struct.unpack('<II', header)
                data = b''
                while len(data) < length:
                    chunk = self.pipe.recv(length - len(data))
                    if not chunk: break
                    data += chunk
                return op, json.loads(data.decode('utf-8'))
        except Exception:
            return None, None

    def _handshake(self):
        self._send(0, {"v": 1, "client_id": self.client_id})
        self._recv()

    def set_activity(self, activity):
        self._send(1, {
            "cmd": "SET_ACTIVITY",
            "args": {
                "pid": os.getpid(),
                "activity": activity
            },
            "nonce": str(time.time())
        })
        return self._recv()

    def close(self):
        try:
            if self.pipe:
                self.pipe.close()
        except Exception:
            pass
        self.pipe = None

def fetch_panel_sync():
    try:
        req = urllib.request.Request(PANEL_URL, headers={"User-Agent": "TigrouRPC-Client/1.0"})
        with urllib.request.urlopen(req, timeout=5) as response:
            if response.status == 200:
                return json.loads(response.read().decode('utf-8'))
    except Exception:
        pass
    return None

def main():
    print("=" * 64)
    print("🐯 TigrouToBombrito - Discord Rich Presence Compte Classique")
    print("=" * 64)
    print("[*] Connexion a l'application Discord locale...")

    ipc = DiscordIPC(CLIENT_ID)
    start_time = int(time.time())

    while True:
        if not ipc.pipe:
            if ipc.connect():
                print("[+] Connecte avec succes a Discord !")
            else:
                print("[-] Discord n'est pas encore detecte. Reessai dans 5s... (Ouvrez Discord)")
                time.sleep(5)
                continue

        sync_data = fetch_panel_sync()
        online_str = "0"
        max_str = "20"
        players_str = "0/20"
        tps_str = "20.0"

        if sync_data:
            online_str = str(sync_data.get('online', 0))
            max_str = str(sync_data.get('max', 20))
            players_str = f"{online_str}/{max_str}"
            tps_str = str(sync_data.get('tps', '20.0'))

        cfg = (sync_data and sync_data.get('config')) or {}
        raw_name = cfg.get('activityName') or 'TigrouToBombrito 1.12.2'
        raw_details = cfg.get('activityDetails') or 'play.tigrou.online'
        raw_state = cfg.get('activityState') or '👥 {players} joueurs | TPS: {tps}'

        def replace_vars(s):
            return s.replace('{online}', online_str).replace('{max}', max_str).replace('{players}', players_str).replace('{tps}', tps_str).replace('{ip}', 'play.tigrou.online')

        details = replace_vars(raw_details)
        state = replace_vars(raw_state)

        activity = {
            "details": details,
            "state": state,
            "timestamps": {"start": start_time},
            "assets": {
                "large_image": "https://cdn.discordapp.com/avatars/1551282825234223234/7d20405d7c73c868ae1cfd81779448b1.png",
                "large_text": "TigrouToBombrito 1.12.2",
                "small_image": "https://mc-heads.net/avatar/MHF_Chest",
                "small_text": "Minecraft Forge"
            },
            "buttons": [
                {"label": "Rejoindre le Serveur", "url": "https://play.tigrou.online"},
                {"label": "Panel Web & Dynmap", "url": "https://tigroutobombrito.tigrou.online"}
            ]
        }

        try:
            op, resp = ipc.set_activity(activity)
            if op is None:
                print("[!] Connexion Discord perdue. Reconnexion...")
                ipc.close()
                time.sleep(3)
                continue
            print(f"[{time.strftime('%H:%M:%S')}] Statut Discord a jour : {details} | {state}")
        except Exception as e:
            print("[!] Erreur envoi:", e)
            ipc.close()

        time.sleep(15)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("
[*] Arret du Rich Presence. A bientot !")
