
import argparse

import os
import signal
import sys
import threading

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from autosklearn.util.logging_ import (
    LogRecordSocketReceiver,
    LogRecordStreamHandler,
    setup_logger,
)


def main():
    parser = argparse.ArgumentParser(description="Start log server")
    parser.add_argument("--host", default="localhost", help="Server address (default: localhost)")
    parser.add_argument("--port", type=int, default=9020, help="Server port (default: 9020)")
    parser.add_argument("--logname", default="autosklearn", help="Log name (default: autosklearn)")
    parser.add_argument("--logfile", default="server.log", help="Log file path (default: server.log)")
    parser.add_argument("--output-dir", default=".", help="Output directory (default: current directory)")
    
    args = parser.parse_args()
    
    # Setup logging configuration
    logging_config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            }
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "INFO",
                "formatter": "default",
                "stream": "ext://sys.stdout"
            },
            "file": {
                "class": "logging.FileHandler",
                "level": "DEBUG",
                "formatter": "default",
                "filename": args.logfile,
                "mode": "a"
            }
        },
        "root": {
            "level": "DEBUG",
            "handlers": ["console", "file"]
        }
    }
    
    # Setup logger
    setup_logger(
        output_dir=args.output_dir,
        filename=args.logfile,
        logging_config=logging_config
    )
    
    # Create stop event
    stop_event = threading.Event()
    
    def signal_handler(sig, frame):
        stop_event.set()
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    print(f"Starting log server...")
    print(f"  Address: {args.host}")
    print(f"  Port: {args.port}")
    print(f"  Log name: {args.logname}")
    print(f"  Log file: {args.logfile}")
    print(f"Press Ctrl+C to stop the server\n")
    
    try:
        # Create and start server
        receiver = LogRecordSocketReceiver(
            host=args.host,
            port=args.port,
            logname=args.logname,
            event=stop_event,
        )
        
        print(f"Server started, waiting for client connections...")
        receiver.serve_until_stopped()
        
    except OSError as e:
        if "Address already in use" in str(e):
            print(f"Error: Port {args.port} is already in use")
            sys.exit(1)
        else:
            print(f"Error: {e}")
            sys.exit(1)
    except KeyboardInterrupt:
        print("\nServer stopped")
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()

