import os
import json
import uuid
import datetime
from typing import Dict, Any, List

class JSONLLogger:
    def __init__(self, log_dir: str = "logs", max_lines: int = 2000):
        self.log_dir = log_dir
        self.max_lines = max_lines
        self.current_lines = 0
        self.current_file = None
        
        os.makedirs(self.log_dir, exist_ok=True)
        self._rotate_file()

    def _rotate_file(self):
        """Creates a new JSONL log file when the line limit is reached."""
        if self.current_file:
            self.current_file.close()
        
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        file_id = str(uuid.uuid4())[:8]
        file_path = os.path.join(self.log_dir, f"xoron_api_{timestamp}_{file_id}.jsonl")
        
        self.current_file = open(file_path, "a")
        self.current_lines = 0
        print(f"[Logger] Started new log file: {file_path}")

    def log_interaction(self, user_id: str, endpoint: str, request_data: Dict[str, Any], response_data: Dict[str, Any]):
        """Logs an interaction to the JSONL file."""
        log_entry = {
            "timestamp": datetime.datetime.utcnow().isoformat() + "Z",
            "user_id": user_id,
            "endpoint": endpoint,
            "request": request_data,
            "response": response_data,
        }
        
        self.current_file.write(json.dumps(log_entry) + "\n")
        self.current_file.flush()
        self.current_lines += 1
        
        if self.current_lines >= self.max_lines:
            self._rotate_file()

    def __del__(self):
        if self.current_file:
            self.current_file.close()
