import re
from datetime import datetime, timedelta
from enum import Enum

from app.config import FILE_LOGGING, LOG_FILE
from app.utils import Result


class AutofixLogger:
    log_file = LOG_FILE
    log_check_period_hours = 24

    @classmethod
    def check_logged_api_reports(
        cls,
        service_codename: str,
        target_status: str = None,
    ) -> Result:
        result = Result(data={"already_sent": False, "timestamp": ""})
        if not FILE_LOGGING:
            result.warnings.append("File logging is disabled")
            return result

        threshold_time = datetime.now() - timedelta(hours=cls.log_check_period_hours)
        pattern = f"{LogPattern.TIMESTAMP.regex}.*?{LogPattern.REPORT_SUCCESS.regex.format(service=service_codename)}"
        if target_status is not None:
            pattern = f"{pattern}{LogPattern.SERVICE_STATUS.regex.format(status=target_status)}"
        try:
            with open(cls.log_file, "r") as file:
                data = file.read()
                matches = re.findall(pattern, data)
        except Exception as err:
            result.message = f"Failed to check log file: {repr(err)}"
            result.success = False
            return result

        if bool(matches):
            timestamp_str = matches[-1].split(",")[0]
            timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
            result.data["already_sent"] = timestamp >= threshold_time
            result.data["timestamp"] = timestamp_str

        return result


class LogPattern(Enum):
    REPORT_SUCCESS = "Report sent for service {service}"
    REPORT_FAIL = "Failed to add service check for {service}"
    TIMESTAMP = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}"
    SERVICE_STATUS = "\s+\\({status}\\)"  # noqa

    @property
    def regex(self) -> str:
        return self.value
