#   Copyright 2021 Modelyst LLC
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from typing import Any
from typing import Generator as GenType
from typing import List, Mapping, Optional

from sqlalchemy.future import Engine
from sqlmodel import Session, func, select

from dbgen.core.metadata import GeneratorEntity, GeneratorRunEntity, RunEntity


def get_runs(
    run_id: Optional[int],
    meta_engine: "Engine",
    all_runs: bool = True,
    accepted_statuses: List[str] = None,
    last: Optional[int] = 1,
) -> GenType[Mapping[str, Any], None, None]:
    statement = select(GeneratorEntity.name, *GeneratorRunEntity.__table__.c).join_from(GeneratorRunEntity, GeneratorEntity).order_by(GeneratorRunEntity.run_id.desc(), GeneratorRunEntity.ordering)  # type: ignore
    if accepted_statuses:
        statement = statement.where(GeneratorRunEntity.status.in_(accepted_statuses))  # type: ignore
    if not all_runs:
        statement = statement.where(
            GeneratorRunEntity.run_id > select(func.max(RunEntity.id)).scalar_subquery() - last  # type: ignore
        )
    with Session(meta_engine) as session:
        result = session.exec(statement).mappings()
        yield from result

sqlmodel.Session dbgen.core.metadata.GeneratorRunEntity.run_id.desc sqlmodel.select sqlmodel.func.max dbgen.core.metadata.GeneratorRunEntity.status.in_
[((1210, 1242), 'dbgen.core.metadata.GeneratorRunEntity.run_id.desc', 'GeneratorRunEntity.run_id.desc', ([], {}), '()\n', (1240, 1242), False, 'from dbgen.core.metadata import GeneratorEntity, GeneratorRunEntity, RunEntity\n'), ((1606, 1626), 'sqlmodel.Session', 'Session', (['meta_engine'], {}), '(meta_engine)\n', (1613, 1626), False, 'from sqlmodel import Session, func, select\n'), ((1351, 1399), 'dbgen.core.metadata.GeneratorRunEntity.status.in_', 'GeneratorRunEntity.status.in_', (['accepted_statuses'], {}), '(accepted_statuses)\n', (1380, 1399), False, 'from dbgen.core.metadata import GeneratorEntity, GeneratorRunEntity, RunEntity\n'), ((1092, 1153), 'sqlmodel.select', 'select', (['GeneratorEntity.name', '*GeneratorRunEntity.__table__.c'], {}), '(GeneratorEntity.name, *GeneratorRunEntity.__table__.c)\n', (1098, 1153), False, 'from sqlmodel import Session, func, select\n'), ((1522, 1544), 'sqlmodel.func.max', 'func.max', (['RunEntity.id'], {}), '(RunEntity.id)\n', (1530, 1544), False, 'from sqlmodel import Session, func, select\n')]