
import io
import os
from sqlalchemy import create_engine, MetaData
from sqlacodegen.codegen import CodeGenerator
import settings
import re
from pathlib import Path
from typing import List
def generate_model()->List:
    engine = create_engine(settings.DBURL.replace('mysql+aiomysql','mysql+pymysql'))
    metadata = MetaData(bind=engine)
    metadata.reflect()
    memoryfile = io.StringIO()
    generator = CodeGenerator(metadata)
    generator.render(memoryfile)

    memoryfile.seek(0)
    newcontent=memoryfile.read()
    #print('newcontet',newcontent)
    oldcontent=''
    if os.path.exists(os.path.join(settings.BASE_DIR,'Models', 'allModels.py.fromdb')):

        with open(os.path.join(settings.BASE_DIR,'Models', 'allModels.py.fromdb'), 'r+', encoding='utf8') as f:
            oldcontent=f.read()

    if newcontent!=oldcontent:
        with open(os.path.join(settings.BASE_DIR,'Models', 'allModels.py.fromdb'), 'w', encoding='utf8') as f:
            f.write(newcontent)

    overwriteclass=["from .ModelBase import Base","from typing import TypeVar",'ModelType = TypeVar("ModelType", bound=Base)']
    allmodelclas=[]
    for tmpfile in Path(settings.BASE_DIR).joinpath('Models').rglob("*.py"):
        if tmpfile.name.endswith('.py') and tmpfile.name not in ['__init__.py','Base.py']:
            with tmpfile.open('rt',encoding='utf8') as tmppyfile:
                content=tmppyfile.read()


                if (tmpclasses:=re.findall(r"^class (.*?)\(Base",content,re.M)):
                    allmodelclas+=tmpclasses
                    overwriteclass.append(f"from .{str(tmpfile.relative_to(os.path.join(settings.BASE_DIR,'Models'))).replace(os.sep,'.')[0:-3]} import {','.join(tmpclasses)}")




    imports='\n'.join(overwriteclass)

    # def getclassname()->str:
    #     classname=",".join(sorted(set(re.findall(r"class (.*?)\(", newcontent)).difference(set(overwriteclass)).union(set(["Base"]))))
    #
    #     return classname
    #imports1=''.join(sorted([f'from .{classname} import {classname}\n' for classname in overwriteclass]))
    #import2=f'from .autogeneratedmodel import ({getclassname()})'
    #imports=imports1+import2

    with open(os.path.join(settings.BASE_DIR,'Models','__init__.py'),'r',encoding='utf8') as f:
        oldimmports=f.read()

    if imports!=oldimmports:
        with open(os.path.join(settings.BASE_DIR, 'Models', '__init__.py'), 'w', encoding='utf8') as f:
            f.write(imports)
    return allmodelclas
if __name__ == '__main__':
    generate_model()
