"""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_api.jsonl      — All Claude/Ollama API interactions
- logs/v3q_queries.jsonl   — All SQL queries executed
"""

from __future__ import annotations

import json
import logging
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)
    app_handler = logging.FileHandler(log_path / "v3q_app.jsonl", encoding="utf-8")
    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.FileHandler(log_path / "v3q_errors.jsonl", encoding="utf-8")
    error_handler.setLevel(logging.WARNING)
    error_handler.setFormatter(json_formatter)
    root_logger.addHandler(error_handler)

    # API interaction log
    api_logger = logging.getLogger("v3q.api")
    api_handler = logging.FileHandler(log_path / "v3q_api.jsonl", encoding="utf-8")
    api_handler.setFormatter(json_formatter)
    api_logger.addHandler(api_handler)

    # Query execution log
    query_logger = logging.getLogger("v3q.queries")
    query_handler = logging.FileHandler(log_path / "v3q_queries.jsonl", encoding="utf-8")
    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)
