import json
import logging
from datetime import datetime
from enum import Enum

from median.utils import get_counter
from flask import Blueprint, request, session
from flask_jwt_extended import jwt_required
from median.constant import MEDIANWEB_POSTE, CONFIG_WEB_CLE
from median.models import (
    DataExtract,
)
from median.views import RawConfig

from common.models import WebLogActions
from common.status import (
    HTTP_200_OK,
    HTTP_500_INTERNAL_SERVER_ERROR,
)
from common.util import mustHaveRights

data_fetcher_blueprint = Blueprint("datafetcher", __name__)

logger = logging.getLogger("median.datafetcher")

RESSOURCE_NAME = "WEB_DATA_FETCHER"


class TargetNames(Enum):
    BAMBERG = "bamberg"


@data_fetcher_blueprint.route("/create_import", methods=["POST"])
@jwt_required()
@mustHaveRights(RESSOURCE_NAME, canView=True)
def start_import():
    try:
        data = json.loads(request.data)
        location_code = data.get("selectedService")

        # Create the import record
        import_id = _create_import(data)
        if not import_id:
            return {"message": "Failed to create import record"}, HTTP_500_INTERNAL_SERVER_ERROR

        # Process the import
        process_success = _process_import(import_id, location_code)
        if not process_success:
            return {"message": "Failed to process import"}, HTTP_500_INTERNAL_SERVER_ERROR

        # Both operations succeeded
        return {"success": True, "message": "Data import completed successfully"}, HTTP_200_OK

    except Exception as error:
        logger.error(f"Data fetcher import failed: {error}")
        return {"message": str(error)}, HTTP_500_INTERNAL_SERVER_ERROR


def _create_import(data):
    try:
        count = get_counter("DATA_ID_IMPORT", force_create=True)

        # Extract form data
        selected_service = data.get("selectedService")
        start_date = data.get("startDate")
        end_date = data.get("endDate", "")
        moments = data.get("moments", [])

        # Get current user from session
        current_user = session["username"]

        # Generate unique import ID using counter
        import_id = count

        # Convert moments array to boolean flags
        moment_morning = 1 if "matin" in moments else 0
        moment_midday = 1 if "midi" in moments else 0
        moment_evening = 1 if "soir" in moments else 0
        moment_night = 1 if "nuit" in moments else 0
        moment_undefined = 1 if not moments else 0

        # Create DataExtract record
        data_extract = DataExtract.create(
            chrono=datetime.now(),
            user=current_user,
            ipp="",  # Empty for service-level import
            ward=selected_service,
            id_import=import_id,
            moment_morning=moment_morning,
            moment_midday=moment_midday,
            moment_evening=moment_evening,
            moment_night=moment_night,
            moment_undefined=moment_undefined,
            date_start=datetime.strptime(start_date, "%Y-%m-%d") if start_date else None,
            date_end=datetime.strptime(end_date, "%Y-%m-%d") if end_date else None,
        )

        logger.info(f"Created DataExtract record with ID: {data_extract.pk}")

        log_data_import(session["username"], "import", f"Asked import with DataExtract record ID = {data_extract.id}")

        return import_id

    except Exception as error:
        logger.error(f"Failed to create import record: {error}")
        return False


def _process_import(import_id: int, location_code: str):
    try:
        target = RawConfig(MEDIANWEB_POSTE, CONFIG_WEB_CLE).read(param="k_web_data_fetch_target")

        if not target:
            # Unable to fetch data, please configure the data targets
            logger.error("Data target configuration is missing")
            return False

        if target.value == TargetNames.BAMBERG.value:
            logger.info("Processing Bamberg data import")
            from .datafetcher_bamberg import BambergDataFetcher

            fetcher = BambergDataFetcher(import_id=import_id, location_code=location_code)

            return fetcher.process_import()

        else:
            logger.info(f"No data processing implemented for target: {target}")
            return True  # Consider this successful for non-Bamberg targets

    except Exception as error:
        logger.error(f"Error during data processing: {error}")
        return False


def log_data_import(username: str, action: str, message: str):
    """
    Add new log for data fetcher

    :param username: User made the action to log
    :param action:
    :param message: message to log
    """
    logger.info("DataFetcher[%s](%s)): %s" % (action, username, message))
    wlog = WebLogActions()
    wlog.chrono = datetime.now()
    wlog.username = username
    wlog.equipement_type = ""
    wlog.action = action
    wlog.message = message
    wlog.save()
