from core import constants, get_available_mods, get_available_server_cfgs, load_config
from core.constants import CATEGORY_OPTIONS, MAP_OPTIONS, TARGET_MOD, UMC_MASTER_FILE
from core.domain.map_queries import get_map_file_count, get_uncategorized_maps
from core.domain.umc_operations import get_category_count
from core.io.umc_parser import parse_umc_file
from core.services.map_install_service import (
    get_available_categories,
    get_sorted_categories_workflow,
)
from core.services.scan_service import get_used_mods
from flask import Blueprint, json, render_template, request

views_bp = Blueprint("views", __name__)


@views_bp.route("/")
def index() -> str:
    """Returns to the app's home screen."""
    return render_template(
        "index.html",
        categoriescount=get_category_count(get_sorted_categories_workflow()),
        mapscount=get_map_file_count(),
        modscount=len(get_available_mods()),
    )


@views_bp.route("/maps")
def maps_dashboard() -> str:
    """Displays the dashboard where configurations are grouped by Map."""
    master_data = {}
    if constants.UMC_MASTER_FILE.exists():
        master_data = parse_umc_file(constants.UMC_MASTER_FILE)

    grouped_maps = {}
    for category_name, cat_content in master_data.items():
        for map_name, map_config in cat_content.get("maps", {}).items():
            if map_name not in grouped_maps:
                grouped_maps[map_name] = {}
            grouped_maps[map_name][category_name] = map_config

    available_mods = get_available_mods()
    used_mods = get_used_mods()
    categories = get_sorted_categories_workflow()
    return render_template(
        "maps_dashboard.html",
        grouped_maps=grouped_maps,
        mods=available_mods,
        categories=sorted(categories),
        used_mods=used_mods,
        mapscount=grouped_maps.__len__(),
        target_mod_names=TARGET_MOD,
        uncategorized_maps=get_uncategorized_maps(master_data),
    )


@views_bp.route("/maps/upload")
def maps_upload() -> str:
    """Return to the standard map-adding screen."""
    return render_template(
        "upload.html",
        categories=get_sorted_categories_workflow(),
        category_options=CATEGORY_OPTIONS,
        map_options=MAP_OPTIONS,
        available_mods=get_available_mods(),
        target_mod_names=TARGET_MOD,
    )


@views_bp.route("/config")
def config() -> str:
    """Returns to the app's config mods screen."""
    config = load_config()
    load_order = config.get("load_order", [])

    available_server_cfgs = get_available_server_cfgs()
    available_server_cfgs.sort()

    available_mods = get_available_mods()

    return render_template(
        "config.html",
        mods=available_mods,
        load_order=load_order,
        server_cfgs=available_server_cfgs,
        categories=get_sorted_categories_workflow(),
    )


@views_bp.route("/categories")
def categories() -> str:
    """Returns to the app's category screen."""
    return render_template(
        "categories.html",
        categories=parse_umc_file(UMC_MASTER_FILE),
        mod_names=TARGET_MOD,
        category_options=CATEGORY_OPTIONS,
        map_options=MAP_OPTIONS,
    )


@views_bp.route("/maps/add_existing", methods=["POST"])
def add_existing_maps() -> str:
    """Returns the page used to add existing maps to another category."""
    selected_maps = json.loads(request.form.get("selected_maps", "[]"))

    return render_template(
        "add_existing_maps.html",
        selected_maps=selected_maps,
        categories=get_available_categories(selected_maps),
        category_options=CATEGORY_OPTIONS,
        map_options=MAP_OPTIONS,
        available_mods=get_available_mods(),
        target_mod_names=TARGET_MOD,
    )
