"""Utility resources for dsd-scalingo."""

import re

from django_simple_deploy.management.commands.utils import plugin_utils


def get_new_apps():
    """Check user's apps, and only consider apps that have a status of `new`."""
    cmd = "scalingo apps"
    output_obj = plugin_utils.run_quick_command(cmd)
    app_names = _get_app_names(output_obj.stdout.decode())
    
    return [app for app in app_names if _get_app_status(app) == "new"]

def get_existing_dbs(app_name):
    """Check addons for this Scalingo app, and return any databases."""
    cmd = f"scalingo addons --app {app_name}"
    output_obj = plugin_utils.run_quick_command(cmd)
    return _parse_existing_dbs(output_obj.stdout.decode())


# --- Helper functions ---

def _get_app_names(output_str):
    """Parse output of `scalingo apps` for project names."""
    if "You haven't created any app yet" in output_str:
        return []

    re_app_names = r"^\u2502 (.*?) \u2502"
    matches = re.finditer(re_app_names, output_str, re.MULTILINE)
    matches = [m.group(1).strip() for m in matches]
    matches.remove("NAME")
    return matches

def _get_app_status(app_name):
    """Get the status of a Scalingo app."""
    cmd = f"scalingo apps-info --app {app_name}"
    output_obj = plugin_utils.run_quick_command(cmd)
    return _parse_status(output_obj.stdout.decode())

def _parse_status(apps_info_string):
    """Parse app status from the result of apps-info."""
    re_status = r"^\u2502 Status\s*\u2502\s*(\S*)\s*\u2502"
    m = re.search(re_status, apps_info_string, re.MULTILINE)
    return m.group(1)

def _parse_existing_dbs(addons_info_string):
    """Parse existing databases from result of `addons`."""
    re_dbs = r"^\u2502 PostgreSQL\s*\u2502\s*\S*\s*\u2502 (\S*)\s*\u2502"
    matches = re.finditer(re_dbs, addons_info_string, re.MULTILINE)
    return [m.group(1) for m in matches]