#!/usr/bin/env python3
import urllib.request
import bz2
import xml.etree.ElementTree as ET
import pymysql
import sys

# Konfiguracja bazy danych
DB_HOST = 'localhost'
DB_USER = 'site_dc24heu_user'
DB_PASSWORD = 'C7tS9uSXDN6vqbBLpnCxj1NsS0kKJntn'
DB_NAME = 'site_dc24heu_db'

# Konfiguracja źródła danych (NOWY ADRES)
HUBLIST_URL = 'https://hublist.pwiam.com/hublist.xml.bz2'

def create_table_if_not_exists(cursor):
    """Tworzy nową tabelę w bazie dla listy PWiAM, jeśli ta jeszcze nie istnieje."""
    create_table_sql = """
    CREATE TABLE IF NOT EXISTS hublist_pwiam_com_downloaded_hubs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255),
        description TEXT,
        users INT DEFAULT 0,
        address VARCHAR(255) UNIQUE,
        country VARCHAR(50),
        shared BIGINT DEFAULT 0,
        min_share BIGINT DEFAULT 0,
        min_slots INT DEFAULT 0,
        max_hubs INT DEFAULT 0,
        max_users INT DEFAULT 0,
        reliability VARCHAR(50),
        rating VARCHAR(50),
        last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    """
    cursor.execute(create_table_sql)

def fetch_and_parse_hublist(url):
    """Pobiera listę hubów i zwraca sparsowane drzewo XML."""
    print(f"Pobieranie listy hubów z: {url} ...")
    try:
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (compatible; DC-Crawler/1.0)'})
        with urllib.request.urlopen(req, timeout=30) as response:
            data = response.read()
            
            if data.startswith(b'BZh'):
                print("Wykryto kompresję bz2. Dekompresowanie...")
                data = bz2.decompress(data)
            
            print("Parsowanie danych XML...")
            return ET.fromstring(data)
    except Exception as e:
        print(f"Błąd podczas pobierania lub parsowania listy: {e}")
        sys.exit(1)

def safe_int(value):
    """Bezpieczna konwersja do int. Zwraca 0 w przypadku braku lub błędu."""
    try:
        return int(value) if value else 0
    except ValueError:
        return 0

def main():
    # Pobieranie danych
    root = fetch_and_parse_hublist(HUBLIST_URL)
    hubs = root.findall('.//Hub')
    
    if not hubs:
        print("Nie znaleziono żadnych hubów na pobranej liście PWiAM.")
        sys.exit(0)
        
    print(f"Znaleziono {len(hubs)} hubów. Łączenie z bazą danych...")

    # Podłączanie do bazy
    try:
        connection = pymysql.connect(
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME,
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )
    except pymysql.MySQLError as e:
        print(f"Błąd połączenia z bazą danych: {e}")
        sys.exit(1)

    try:
        with connection.cursor() as cursor:
            # Tworzenie nowej tabeli
            create_table_if_not_exists(cursor)
            
            # Wstawianie lub aktualizacja danych w nowej tabeli
            insert_sql = """
            INSERT INTO hublist_pwiam_com_downloaded_hubs 
            (name, description, users, address, country, shared, min_share, min_slots, max_hubs, max_users, reliability, rating)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
            name=VALUES(name), description=VALUES(description), users=VALUES(users), country=VALUES(country),
            shared=VALUES(shared), min_share=VALUES(min_share), min_slots=VALUES(min_slots),
            max_hubs=VALUES(max_hubs), max_users=VALUES(max_users), reliability=VALUES(reliability), rating=VALUES(rating);
            """
            
            inserted_count = 0
            for hub in hubs:
                name = hub.get('Name', '')
                description = hub.get('Description', '')
                users = safe_int(hub.get('Users'))
                address = hub.get('Address', '')
                country = hub.get('Country', '')
                shared = safe_int(hub.get('Shared'))
                min_share = safe_int(hub.get('MinShare'))
                min_slots = safe_int(hub.get('MinSlots'))
                max_hubs = safe_int(hub.get('MaxHubs'))
                max_users = safe_int(hub.get('MaxUsers'))
                reliability = hub.get('Reliability', '')
                rating = hub.get('Rating', '')

                if not address:
                    continue

                cursor.execute(insert_sql, (
                    name, description, users, address, country, shared, 
                    min_share, min_slots, max_hubs, max_users, reliability, rating
                ))
                inserted_count += 1
            
            connection.commit()
            print(f"Zakończono sukcesem. Zapisano/Zaktualizowano {inserted_count} hubów z listy PWiAM w bazie danych.")
            
    except Exception as e:
        print(f"Wystąpił błąd bazy danych: {e}")
    finally:
        connection.close()

if __name__ == '__main__':
    main()
