from argparse import (
    ArgumentParser,
    ArgumentDefaultsHelpFormatter,
    RawDescriptionHelpFormatter
)
from dataclasses import dataclass
from http.server import HTTPServer
from io import BytesIO, IOBase
from typing import Optional, Tuple, List

from byteb4rb1e.utils.http.server import (
    HandlerOptions,
    MultipartUploadHandler,
    ServerOptions,
)
from byteb4rb1e.utils.io import ChunksIO


__doc__ = """tsmuds - Tiara's Simple Multipart Upload Debugging Server

This is a simple standalone implementation of a HTTP/1.x multipart upload server
using the Python 3.9+ standard library - with an interface catered explicitly
towards debugging misbehaved clients.

Examples:

    python3 tsmuds.py --port 8000
"""
__author__ = "Tiara Rodney <tiara.rodney@administratrix.de>"


class CustomArgparseFormatter(
    ArgumentDefaultsHelpFormatter, 
    RawDescriptionHelpFormatter
):
    """custom formatter that shows defaults for arguments as well as keeps
    my docstring unformatted.
    """


argparser = ArgumentParser(
    prog = 'byteb4rb1e.http.server',
    formatter_class = CustomArgparseFormatter,
    description = __doc__,
    epilog = f"""(c) 2025, {__author__}

This software is licensed under the Creative Commons Attribution 4.0
International License (CC BY 4.0). For more details, visit:
https://creativecommons.org/licenses/by/4.0/
"""
)

argparser.add_argument(
    '--port',
    type=int,
    default=ServerOptions.port,
    help="bind to this port"
)

argparser.add_argument(
    '-b',
    '--bind',
    type=str,
    default=ServerOptions.hostname,
    help="bind to this address"
)

argparser.add_argument(
    '--max-chunk-size',
    type=int,
    metavar='INT',
    default=(ChunksIO.max_chunk_size / (1024 ** 2)),
    help="""maximum allowed size of chunk (in MiB) when RFC 9112 chunk
            transfer encoding is requested by client"""
)

args = argparser.parse_args()

server_options = ServerOptions(
    port = args.port,
    handler = HandlerOptions(
        max_chunk_size = args.max_chunk_size
    ),
)

with HTTPServer(server_options, MultipartUploadHandler) as httpd:
    print("serving at port", server_options.port)
    httpd.serve_forever()
