#!/usr/bin/env python3

import asyncio
import datetime
import json
import os
import time
from argparse import ArgumentParser
from collections.abc import Sequence

import httpx
import uvloop
from dotenv import load_dotenv
from loguru import logger
from sqlmodel import Session, create_engine

from steam2sqlite import APPIDS_URL, BATCH_SIZE, navigator, utils
from steam2sqlite.handler import (
    get_appids_from_db,
    get_apps_achievements,
    get_apps_data,
    get_error_appids,
    store_apps_achievements,
    store_apps_data,
)

load_dotenv()

APPIDS_FILE = os.getenv("APPIDS_FILE")

sqlite_file_name = "database.db"
SQLITE_URL = f"sqlite:///{sqlite_file_name}"


async def get_appids_from_steam(local_file: str = None) -> dict[int, str]:
    if local_file:
        logger.info(f"Loading appids from local file: {local_file}")
        with open(local_file) as steam_appids_fp:
            appid_data = json.load(steam_appids_fp)
    else:
        logger.info("Loading appids from Steam API")
        try:
            async with httpx.AsyncClient() as client:
                resp = await navigator.get(client, APPIDS_URL)
            appid_data = resp.json()
            await asyncio.sleep(1)
        except navigator.NavigatorError:
            logger.error("Error getting the appids from Steam")
            raise

    return {item["appid"]: item["name"] for item in appid_data["applist"]["apps"]}


def main(argv: Sequence[str] | None = None) -> int:

    parser = ArgumentParser()
    parser.add_argument(
        "-l",
        "--limit",
        type=float,
        default=None,
        nargs="?",
        const=1,
        help="limit runtime (minutes)",
    )
    args = parser.parse_args(argv)

    logger.info("Starting...")

    start_time = time.monotonic()

    uvloop.install()

    engine = create_engine(SQLITE_URL, echo=False)

    # From steam api, dict of: {appids: names}
    steam_appids_names = asyncio.run(get_appids_from_steam(APPIDS_FILE))

    with 