import os
from .argument import ArgParser, Mode
import sys

APP = {
    "apis.py": """

    """,
    "models.py": """
    
    """,
    "serializer.py": """
    
    """,
    "urls.py": """
{}_urls = {

}
    """,
}

PROJECT = {
    "core": {
        "configs.py": """
'''
Generated by Panther
'''

from pathlib import Path
from dotenv import dotenv_values


DEBUG = False  # DEBUG default is False
BASE_DIR = Path(__name__).resolve().parent
env = dotenv_values(BASE_DIR / '.env')

DB_NAME = env['DB_NAME']
DB_HOST = env['DB_HOST']
DB_PORT = env['DB_PORT']
SECRET_KEY = env['SECRET_KEY']
DB_USERNAME = env['DB_USERNAME']
DB_PASSWORD = env['DB_PASSWORD']

URLs = 'core/urls.py'
        """,
        "middlewares.py": """
from panther.middlewares import BaseMiddleware


class InitialMiddleware(BaseMiddleware):
    ...
        """,
        "urls.py": """
urls = {

}
        """,
    },
    ".env": """
SECRET_KEY = "THIS IS MY SECRET SECRET KEY"

DB_NAME = "panther"
DB_HOST = "127.0.0.1"
DB_PORT = "27017"
DB_USERNAME = ""
DB_PASSWORD = ""
    """,

    "alembic.ini": """
    
    """,

    "main.py": """
from panther import Panther
import uvicorn

app = Panther(__name__)

if __name__ == "__main__":
    uvicorn.run("main:app")

    """
}


def create_app(name: list | str, path: str):
    os.mkdir(f"{path}/{name}")
    for filename, data in APP.items():
        file = open(f"{path}/{name}/{filename}", 'x')
        file.write(data.replace("{}", "APPNAME"))
        file.close()


def create_project(name: list | str, path: str):
    project_path = f"{path}/{name}"
    os.mkdir(project_path)
    for filename, data in PROJECT.items():
        
        if isinstance(data, dict):
            sub_folder = f"{project_path}/{filename}"
            os.mkdir(sub_folder)
            for new_file, data in data.items():
                file = open(f"{sub_folder}/{new_file}", 'x')
                file.write(data)
                file.close()
        else:
            file = open(f"{project_path}/{filename}", 'x')
            file.write(data.replace("{}", name))
            file.close()


def main():
    ap = ArgParser(os.getcwd())
    ap.add_arg(
        name="app",
        desc="create app template folder",
        mode=Mode.INPUT,
        func=create_app,
    )
    ap.add_arg(
        name="project",
        desc="create project template folder",
        mode=Mode.INPUT,
        func=create_project,
    )
    ap.parser(sys.argv)
