import argparse
import asyncio
import os
from typing import Sequence, Type

from clarabot_nano_common.common.config.constants import CommonConfigConstants
from clarabot_nano_common.server.base.handler.base import AbstractNanoServerHandler
from clarabot_nano_common.utility.path.resolve import resolve_path

from clarabot_nano.common.spawn.constants import ShortNames
from clarabot_nano.development.common import load_development_server_config
from clarabot_nano.development.spawn.common import write_spawn_debug_info
from clarabot_nano.development.spawn.server.document.dbg_handlers import (
    DebugInternalAuthInfoHandler,
    DebugStoreWopiTemplateHandler,
)
from clarabot_nano.server.document.process import DocumentServerProcess


class _TestingDocumentServerProcess(DocumentServerProcess):
    def _init_get_handler_classes(self) -> Sequence[Type[AbstractNanoServerHandler]]:
        hs = [DebugInternalAuthInfoHandler, DebugStoreWopiTemplateHandler]
        hs.extend(DocumentServerProcess._init_get_handler_classes(self))
        return hs


async def startup(development_server_config):
    load_development_server_config(development_server_config)
    with _TestingDocumentServerProcess.create(ShortNames.DOCUMENT_SERVER) as proc:
        config_dir = resolve_path(proc.get_config()["local"]["config_dir"], strict=True)
        write_spawn_debug_info(config_dir, os.getpid(), ShortNames.DOCUMENT_SERVER)
        await proc.run()


def main():
    CommonConfigConstants.DEVELOPMENT = True
    parser = argparse.ArgumentParser("Clarabot Nano - Test Server process (document)")
    parser.add_argument("development_server_config")
    args = parser.parse_args()
    asyncio.run(startup(args.development_server_config))


if __name__ == "__main__":
    main()
