from datetime import datetime
from pathlib import Path

from aiohttp import web


def write(channel, msg, logs_dir):
    path = Path(logs_dir) / channel / f'{datetime.utcnow().date()}.log'
    path.parent.mkdir(parents=True, exist_ok=True)

    with path.open('a') as f:
        f.write(msg)
        f.write('\n')


async def handle(request: web.Request):
    channel = request.match_info['channel']
    write(channel, await request.text(), request.app['logs_dir'])
    return web.Response()


def create_app(dir_path):
    app = web.Application()
    app['logs_dir'] = dir_path
    app.add_routes([web.post('/{channel}', handle)])
    return app
