from defence360agent.contracts.config import UserType
from defence360agent.rpc_tools.middleware import (
    default_to_items as items_middleware,
)
from imav.simple_rpc.schema import init_validator as init_base_validator
from im360.simple_rpc.middleware import (
    add_strategy,
    replace_gray_splashscreen_with_gray,
)


def init_validator(schema_validator, validate_middleware, schema_paths):
    validator, middleware, middleware_exclude = init_base_validator(
        schema_validator, validate_middleware, schema_paths
    )
    strategy_middleware = (add_strategy, (UserType.ROOT,))
    gray_splashscreen_middleware = (
        replace_gray_splashscreen_with_gray,
        (UserType.ROOT,),
    )
    # find index with the items middleware
    i = next(
        i for i, (m, _) in enumerate(middleware[None]) if m is items_middleware
    )
    # insert middlewares before the items middleware
    middleware[None].insert(i, strategy_middleware)
    middleware[None].insert(i, gray_splashscreen_middleware)

    return validator, middleware, middleware_exclude
