# Copyright (c) 2025 CoReason, Inc.
#
# This software is proprietary and dual-licensed.
# Licensed under the Prosperity Public License 3.0 (the "License").
# A copy of the license is available at https://prosperitylicense.com/versions/3.0.0
# For details, see the LICENSE file.
# Commercial use beyond a 30-day trial requires a separate license.
#
# Source Code: https://github.com/CoReason-AI/coreason_mcp

import sys
from pathlib import Path
from typing import Any

from loguru import logger

__all__ = ["logger"]

# Remove default handler
logger.remove()


def scrub_sensitive_data(data: Any) -> Any:
    """Recursively redact sensitive keys and truncate long values."""
    if isinstance(data, dict):
        new_data = {}
        for k, v in data.items():
            if k in ("user_context", "__coreason_context__"):
                new_data[k] = "<REDACTED_SENSITIVE>"
            elif k in ("content", "body", "original_text", "data") and isinstance(v, str) and len(v) > 256:
                new_data[k] = "<TRUNCATED_FOR_COMPLIANCE>"
            else:
                new_data[k] = scrub_sensitive_data(v)
        return new_data
    elif isinstance(data, list):
        return [scrub_sensitive_data(item) for item in data]
    return data


def compliance_filter(record: Any) -> None:
    """Patch log records to redact sensitive data in 'extra' fields."""
    if "extra" in record:
        record["extra"] = scrub_sensitive_data(record["extra"])


# Patch the logger to apply the filter
logger = logger.patch(compliance_filter)

# Sink 1: Stdout (Human-readable)
logger.add(
    sys.stderr,
    level="INFO",
    format=(
        "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
        "<level>{message}</level>"
    ),
)

# Ensure logs directory exists
log_path = Path("logs")
if not log_path.exists():
    log_path.mkdir(parents=True, exist_ok=True)

# Sink 2: File (JSON, Rotation, Retention)
logger.add(
    "logs/app.log",
    rotation="500 MB",
    retention="10 days",
    serialize=True,
    enqueue=True,
    level="INFO",
)
