import os
import time
import uuid
import json
import logging
from datetime import date, datetime, timedelta
from logging.handlers import TimedRotatingFileHandler
from urllib.parse import parse_qsl, urlsplit

from flask import request, g
from modules.core import storage_paths

# Content-Security-Policy.
# ENFORCED: only directives that cannot affect the current front end (no plug-ins, no <base> hijack, framing = same origin as the
# existing X-Frame-Options). Adding script-src / default-src here needs a front-end review: the pages still use inline scripts.
CSP_ENFORCED = "object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
# REPORT-ONLY: the stricter policy under evaluation (browsers log violations in the console; nothing is blocked). Hosts are the CDNs the
# templates really load from; verified embeds only for frames.
CSP_REPORT_ONLY = (
    "default-src 'self'; "
    "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com https://analytics.investment-nieruchomosci.com; "
    "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; "
    "font-src 'self' data:; "
    "img-src 'self' data: blob: https:; media-src 'self' https:; connect-src 'self' https://analytics.investment-nieruchomosci.com; "
    "frame-src 'self' https://www.youtube.com https://www.youtube-nocookie.com https://player.vimeo.com; "
    "object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
)


# =========================
# LOGGERS
# =========================
# Handlers are attached by configure_logging(), called from create_app()
# once configuration (DATA_DIR) is loaded -- importing this module must not
# resolve runtime paths or create log directories.

root_logger = logging.getLogger()
root_logger.setLevel(logging.ERROR)

access_logger = logging.getLogger("access")
access_logger.setLevel(logging.INFO)

access_error_logger = logging.getLogger("access_errors")
access_error_logger.setLevel(logging.INFO)

login_logger = logging.getLogger("login")
login_logger.setLevel(logging.INFO)


class AgeRetainedTimedRotatingFileHandler(TimedRotatingFileHandler):
    """Daily rotation whose backups expire by their date suffix, not file count."""

    def __init__(self, filename, *, retention_days: int, **kwargs):
        self.retention_days = int(retention_days)
        super().__init__(filename, backupCount=0, **kwargs)

    def _expired_backups(self, *, today: date | None = None):
        today = today or date.today()
        cutoff = today - timedelta(days=self.retention_days)
        directory = os.path.dirname(self.baseFilename) or "."
        prefix = os.path.basename(self.baseFilename) + "."
        expired = []
        try:
            entries = os.scandir(directory)
        except OSError:
            return expired
        with entries:
            for entry in entries:
                if not entry.is_file() or not entry.name.startswith(prefix):
                    continue
                suffix = entry.name[len(prefix):]
                try:
                    rotated_day = datetime.strptime(suffix, "%Y-%m-%d").date()
                except ValueError:
                    continue
                if rotated_day < cutoff:
                    expired.append(entry.path)
        return expired

    def prune_expired_backups(self, *, today: date | None = None):
        for filename in self._expired_backups(today=today):
            try:
                os.remove(filename)
            except FileNotFoundError:
                continue

    def doRollover(self):
        super().doRollover()
        self.prune_expired_backups()


def _daily_handler(filename, *, retention_days: int):
    handler = AgeRetainedTimedRotatingFileHandler(
        filename,
        when="midnight",
        interval=1,
        retention_days=retention_days,
        encoding="utf-8",
    )
    handler.prune_expired_backups()
    return handler


def configure_logging():
    log_dir = str(storage_paths.website_logs_dir())
    os.makedirs(log_dir, exist_ok=True)
    error_log_path = str(storage_paths.error_log_path())

    # The dedicated access/access-error/login records terminate at their own
    # file handlers; without this they also propagate to the root logger and
    # thus into error.log and any root StreamHandler (e.g. one installed by a
    # third-party logging.basicConfig), producing duplicated/stderr access
    # lines. Error logging goes to the root logger directly and is unaffected.
    access_logger.propagate = False
    access_error_logger.propagate = False
    login_logger.propagate = False

    # =========================
    # ERROR LOGGER
    # =========================

    if not any(
        isinstance(handler, TimedRotatingFileHandler)
        and os.path.abspath(getattr(handler, "baseFilename", "")) == os.path.abspath(error_log_path)
        for handler in root_logger.handlers
    ):
        error_handler = _daily_handler(
            error_log_path,
            retention_days=90,
        )
        error_handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
        )
        root_logger.addHandler(error_handler)

    # =========================
    # ACCESS LOGGER
    # =========================

    if not access_logger.handlers:
        access_handler = _daily_handler(
            os.path.join(log_dir, "access.log"),
            retention_days=30,
        )
        access_handler.setFormatter(
            logging.Formatter("%(message)s")
        )
        access_logger.addHandler(access_handler)

    if not access_error_logger.handlers:
        access_error_handler = _daily_handler(
            os.path.join(log_dir, "access_errors.log"),
            retention_days=90,
        )
        access_error_handler.setFormatter(
            logging.Formatter("%(message)s")
        )
        access_error_logger.addHandler(access_error_handler)

    # =========================
    # LOGIN LOGGER
    # =========================

    if not login_logger.handlers:
        login_handler = _daily_handler(
            os.path.join(log_dir, "login_attempts.log"),
            retention_days=90,
        )
        login_handler.setFormatter(
            logging.Formatter("%(asctime)s %(message)s")
        )
        login_logger.addHandler(login_handler)


# =========================
# TIMER
# =========================

def start_timer():
    g.start_time = time.perf_counter()
    g.request_id = uuid.uuid4().hex[:12]


def sanitize_query_string(query_string: bytes) -> str:
    """Keep bounded parameter names only; values never enter request logs."""
    raw = query_string.decode("utf-8", errors="replace")
    if not raw:
        return ""

    keys = []
    for key, _value in parse_qsl(raw, keep_blank_values=True):
        normalized = key.strip()
        if normalized and len(normalized) <= 64 and normalized.replace("_", "").replace("-", "").replace(".", "").isalnum():
            keys.append(normalized)
    return "&".join(dict.fromkeys(keys))


def minimize_referrer(value: str | None) -> str:
    try:
        parsed = urlsplit(str(value or ""))
    except ValueError:
        return "-"
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        return "-"
    return f"{parsed.scheme}://{parsed.netloc}/"


def _single_line(value, limit=256) -> str:
    return str(value or "").replace("\r", " ").replace("\n", " ")[:limit]


def get_client_ip() -> str:
    xff = request.headers.get("X-Forwarded-For", "")
    if xff:
        first_ip = xff.split(",")[0].strip()
        if first_ip:
            return first_ip

    xri = request.headers.get("X-Real-IP", "").strip()
    if xri:
        return xri

    return request.remote_addr or "-"


# =========================
# LOGIN ATTEMPTS
# =========================

def log_login_attempt(username, success):
    request_id = getattr(g, "request_id", "-")
    status_text = "SUCCESS" if success else "FAILURE"
    ip = get_client_ip()
    user_agent = _single_line(request.user_agent.string)

    log_line = (
        f'LOGIN_ATTEMPT | {status_text} | USER="{_single_line(username, 128)}" '
        f'REQUEST_ID={request_id} '
        f'IP={ip} USER_AGENT="{user_agent}"'
    )

    login_logger.info(log_line)


# =========================
# AFTER REQUEST
# =========================

def after_request(response):
    path = request.path
    skip_paths = ["/favicon.ico", "/robots.txt", "/sitemap.xml"]

    should_skip_logging = (
        path.startswith("/static/")
        or path.startswith("/api/")
        or path in skip_paths
    )

    if not should_skip_logging:
        duration = round((time.perf_counter() - g.start_time) * 1000)
        is_error = response.status_code >= 400

        log_entry = {
            "datetime": datetime.now().isoformat(timespec="seconds"),
            "request_id": getattr(g, "request_id", "-"),
            "ip": get_client_ip() if is_error else "-",
            "method": request.method,
            "path": path,
            "query": sanitize_query_string(request.query_string),
            "status": response.status_code,
            "referer": minimize_referrer(request.referrer),
            "lang": request.accept_languages.best or "-",
            "response_time_ms": duration,
            "user_agent": _single_line(request.user_agent.string) if is_error else "-",
        }

        access_logger.info(json.dumps(log_entry, ensure_ascii=False))
        if response.status_code >= 400:
            access_error_logger.info(json.dumps(log_entry, ensure_ascii=False))

    # =========================
    # SECURITY HEADERS
    # =========================

    response.headers["Strict-Transport-Security"] = (
        "max-age=31536000; includeSubDomains"
    )
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
    response.headers["Permissions-Policy"] = (
        "geolocation=(), microphone=(), camera=()"
    )
    # Responses that set their own policy (e.g. downloaded documents: `default-src 'none'; sandbox`) are left alone.
    if "Content-Security-Policy" not in response.headers:
        response.headers["Content-Security-Policy"] = CSP_ENFORCED
        response.headers["Content-Security-Policy-Report-Only"] = CSP_REPORT_ONLY

    return response
