"""
Main entry point for the DecentraBrowser client application.
"""
import os
import sys
import argparse
from PyQt5.QtWidgets import QApplication

from ..shared.utils import setup_logging, ensure_directory_exists, get_data_dir
from ..shared.security import SecurityManager
from ..shared.ddns import DDNS
from ..shared.constants import DEFAULT_PORT, DEFAULT_CENTRAL_SERVER_PORT
from .network.http_server import DomainServer
from .network.client import NetworkClient
from .gui.main_window import MainWindow

# Setup logger
logger = setup_logging('client_app')

def main():
    """Entry point for the client application."""
    parser = argparse.ArgumentParser(description='DecentraBrowser Client')
    parser.add_argument('--port', type=int, default=DEFAULT_PORT,
                        help=f'Port to listen on (default: {DEFAULT_PORT})')
    parser.add_argument('--central-server', type=str, default='localhost',
                        help='Central server hostname (default: localhost)')
    parser.add_argument('--central-port', type=int, default=DEFAULT_CENTRAL_SERVER_PORT,
                        help=f'Central server port (default: {DEFAULT_CENTRAL_SERVER_PORT})')
    parser.add_argument('--data-dir', type=str, default=None,
                        help='Data directory (default: platform-specific user data dir)')
    
    args = parser.parse_args()
    
    # Setup data directory
    if args.data_dir:
        data_dir = args.data_dir
    else:
        data_dir = get_data_dir()
    
    ensure_directory_exists(data_dir)
    
    # Setup directories
    certs_dir = ensure_directory_exists(os.path.join(data_dir, 'certs'))
    content_dir = ensure_directory_exists(os.path.join(data_dir, 'content'))
    downloads_dir = ensure_directory_exists(os.path.join(data_dir, 'downloads'))
    
    # Setup DDNS
    ddns_file = os.path.join(data_dir, 'ddns.json')
    ddns = DDNS(ddns_file)
    
    # Setup security manager
    security_manager = SecurityManager(certs_dir)
    
    # Create RSA key pair if not exists
    if not os.path.exists(os.path.join(certs_dir, 'private_key.pem')):
        private_key, public_key = security_manager.generate_rsa_keypair()
        security_manager.save_private_key(private_key, 'private_key.pem')
        security_manager.save_public_key(public_key, 'public_key.pem')
        logger.info("Generated new RSA key pair")
    
    # Create domain server
    domain_server = DomainServer(None, security_manager, content_dir, port=args.port)
    
    # Create network client
    network_client = NetworkClient(security_manager, ddns, args.central_server, args.central_port)
    
    # Create and run application
    app = QApplication(sys.argv)
    main_window = MainWindow(network_client, domain_server, security_manager, ddns, content_dir)
    
    return app.exec_()

if __name__ == '__main__':
    sys.exit(main())