#!/bin/bash

root=${1:-app}
app_py_path="${root//\//.}"
app_py_path="${app_py_path#.}"
app_py_path="${app_py_path%.}"

dirs=(
    "$root"
    "$root/core"
    "$root/core/models"
    "$root/core/schemas"
    "$root/tests"
    "$root/tests/v1"
    "$root/v1"
    "$root/v1/dependencies"
    "$root/v1/routers"
    "$root/v1/internal"

)

declare -A files


files=(
    ["$root/main.py"]="
from fastapi import FastAPI
from $app_py_path.v1 import routers

app = FastAPI()

app.include_router(
    routers.router,
    prefix='/v1',
    tags=['v1'],
)
"
    ["$root/core/settings.py"]="
    DEBUG = True
"
    ["$root/v1/routers/__init__.py"]="
from fastapi import APIRouter
import glob, os
from morm.utils import import_from_path

router = APIRouter()

__all_router_paths = []
for file in glob.glob(os.path.join(os.path.dirname(__file__), '*.py')):
    if file.endswith('__init__.py'):
        continue
    __all_router_paths.append(file)
sorted(__all_router_paths)
for file in __all_router_paths:
    module = import_from_path('tmp', file)
    router.include_router(module.router)
del __all_router_paths

"
    ["$root/tests/v1/test_sample.py"]="
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_sample():
    response = client.get('/')
    assert response.status_code == 200
    assert response.json() == {'msg': 'Hello World'}
"

)

for dir in "${dirs[@]}"; do
    mkdir -p "$dir"
    file="$dir/__init__.py"
    echo "${files[$file]}" > "$file"
done

for key in "${!files[@]}"; do
    if [[ -f "$key" ]]; then
        echo "File exists: $key"
        continue
    fi
    echo "${files[$key]}" > "$key"
done

morm_admin init
