import json
import asyncio
import aiohttp
import requests
import os
import logging

logging.getLogger('aiohttp').setLevel(logging.CRITICAL)
logging.getLogger('asyncio').setLevel(logging.CRITICAL)

class Axiron:
    def __init__(self):
        self.data_path = os.path.join(os.path.dirname(__file__), 'wmn-data.json')
        # Daha sağlam bir User-Agent
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        }

    def EmailAxi(self, email):
        url = f"https://api.xposedornot.com/v1/check-email/{email}"
        try:
            r = requests.get(url, timeout=10)
            if r.status_code == 200:
                d = r.json()
                breaches = d.get("breaches", [[]])[0]
                return {"status": "leaked", "count": len(breaches), "sources": breaches}
            return {"status": "secure", "sources": []}
        except:
            return {"status": "error"}

    async def _check_site(self, sem, session, site, username):
        async with sem:
            url = site['uri_check'].replace("{account}", username)
            try:
                async with session.get(url, timeout=5, ssl=False, allow_redirects=True) as resp:
                    text = await resp.text()
                    found = False
                    
                    if 'e_string' in site and site['e_string'] in text:
                        found = True
                    elif resp.status == site.get('e_code', 200):
                        if 'm_string' in site and site['m_string'] not in text:
                            found = True
                        elif 'm_string' not in site:
                            found = True
                    
                    if found:
                        return {"platform": site['name'], "link": url}
            except:
                pass
            return None

    async def run_osi(self, username):
        if not os.path.exists(self.data_path):
            print(f"[!] HATA: {self.data_path} bulunamadı!")
            return []

        with open(self.data_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        sem = asyncio.Semaphore(15)

        connector = aiohttp.TCPConnector(limit=15, force_close=True)
        
        async with aiohttp.ClientSession(connector=connector, headers=self.headers) as session:
            tasks = [self._check_site(sem, session, site, username) for site in data['sites']]
            search_results = await asyncio.gather(*tasks, return_exceptions=True)
            return [r for r in search_results if isinstance(r, dict) and r is not None]

def EmailAxi(email):
    return Axiron().EmailAxi(email)

def OsiAxi(username):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        return loop.run_until_complete(Axiron().run_osi(username))
    finally:
        loop.close()