"""Structured logging configuration for V3Q.AI.

Logs are stored as JSON-lines files that can be fed directly into Claude Code
for analysis, debugging, and auto-improvement — even from machines where
Claude Code is not installed.

Log levels:
- ERROR: Failures that need fixing
- WARNING: Potential issues, degraded behavior
- INFO: Normal operations, sync events, queries
- DEBUG: Detailed diagnostic info

Files:
- logs/v3q_errors.jsonl   — Errors only (priority feed for Claude Code)
- logs/v3q_app.jsonl      — All app logs
- logs/v3q_sync.jsonl     — All sync/remote/local DB operations (dedicated)
- logs/v3q_api.jsonl      — All Claude/Ollama API interactions
- logs/v3q_queries.jsonl   — All SQL queries executed

All log files use RotatingFileHandler to prevent unbounded growth.
"""

from __future__ import annotations

import json
import logging
import logging.handlers
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


class JSONLineFormatter(logging.Formatter):
    """Format log records as JSON lines — directly feedable to Claude Code."""

    def format(self, record: logging.LogRecord) -> str:
        log_entry = {
            "timestamp": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(),
            "level": record.levelname,
            "logger": record.name,
            "message": record.getMessage(),
            "module": record.module,
            "function": record.funcName,
            "line": record.lineno,
        }

        # Include exception info
        if record.exc_info and record.exc_info[1]:
            log_entry["exception"] = {
                "type": type(record.exc_info[1]).__name__,
                "message": str(record.exc_info[1]),
                "traceback": self.formatException(record.exc_info),
            }

        # Include extra fields (for structured data like SQL, request info, etc.)
        for key in ("sql", "duration_ms", "row_count", "request_id",
                     "conversation_id", "user_question", "error_type",
                     "component", "action", "details"):
            if hasattr(record, key):
                log_entry[key] = getattr(record, key)

        return json.dumps(log_entry, default=str, ensure_ascii=False)


def setup_logging(log_dir: str = "logs", debug: bool = False) -> None:
    """Configure structured logging with JSON-lines output.

    Creates log files that can be fed into Claude Code for debugging:
      cat logs/v3q_errors.jsonl | claude "Analyze these errors and suggest fixes"
    """
    log_path = Path(log_dir)
    log_path.mkdir(parents=True, exist_ok=True)

    json_formatter = JSONLineFormatter()
    console_formatter = logging.Formatter(
        "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG if debug else logging.INFO)

    # Console handler (human-readable)
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG if debug else logging.INFO)
    console_handler.setFormatter(console_formatter)
    root_logger.addHandler(console_handler)

    # Main app log (JSON-lines) — rotated at 50MB, keep 5 backups
    app_handler = logging.handlers.RotatingFileHandler(
        log_path / "v3q_app.jsonl", encoding="utf-8",
        maxBytes=50 * 1024 * 1024, backupCount=5,
    )
    app_handler.setLevel(logging.INFO)
    app_handler.setFormatter(json_formatter)
    root_logger.addHandler(app_handler)

    # Errors only (JSON-lines) — PRIORITY feed for Claude Code
    error_handler = logging.handlers.RotatingFileHandler(
        log_path / "v3q_errors.jsonl", encoding="utf-8",
        maxBytes=10 * 1024 * 1024, backupCount=5,
    )
    error_handler.setLevel(logging.WARNING)
    error_handler.setFormatter(json_formatter)
    root_logger.addHandler(error_handler)

    # Sync-specific log — all sync/remote/local DB operations in one place
    sync_handler = logging.handlers.RotatingFileHandler(
        log_path / "v3q_sync.jsonl", encoding="utf-8",
        maxBytes=50 * 1024 * 1024, backupCount=5,
    )
    sync_handler.setLevel(logging.DEBUG)
    sync_handler.setFormatter(json_formatter)
    for sync_logger_name in (
        "database.remote_executor", "database.local_pg", "database.schema_reader",
        "database.connection_manager", "sync.table_sync", "sync.sync_jobs",
    ):
        logging.getLogger(sync_logger_name).addHandler(sync_handler)

    # API interaction log
    api_logger = logging.getLogger("v3q.api")
    api_handler = logging.handlers.RotatingFileHandler(
        log_path / "v3q_api.jsonl", encoding="utf-8",
        maxBytes=10 * 1024 * 1024, backupCount=3,
    )
    api_handler.setFormatter(json_formatter)
    api_logger.addHandler(api_handler)

    # Query execution log
    query_logger = logging.getLogger("v3q.queries")
    query_handler = logging.handlers.RotatingFileHandler(
        log_path / "v3q_queries.jsonl", encoding="utf-8",
        maxBytes=10 * 1024 * 1024, backupCount=3,
    )
    query_handler.setFormatter(json_formatter)
    query_logger.addHandler(query_handler)

    # Suppress noisy third-party loggers
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)
