# browser_log_api.py - API endpoint for receiving browser logs
from fastapi import APIRouter, Request
import json
import os
from collections import OrderedDict

router = APIRouter()

LOG_FILE = "browser_logs.log"

@router.post("/api/logs/browser")
async def receive_browser_logs(request: Request):
    data = await request.json()
    logs = data.get("logs", [])
    print("[DEBUG] Received logs:", json.dumps(logs, ensure_ascii=False, indent=2))  # Debug: print received logs
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        for log in logs:
            # Move timestamp to the start using OrderedDict
            formatted_log = OrderedDict()
            if 'timestamp' in log:
                formatted_log['timestamp'] = log['timestamp']
            for k, v in log.items():
                if k != 'timestamp':
                    formatted_log[k] = v
            # Pretty-print stackTree if present
            if 'stackTree' in formatted_log and isinstance(formatted_log['stackTree'], str):
                try:
                    formatted_log['stackTree'] = json.loads(formatted_log['stackTree'])
                except Exception:
                    pass
            # Write log entry as pretty JSON (stackTree will be multi-line if present)
            f.write(json.dumps(formatted_log, ensure_ascii=False, indent=2) + "\n")
            print(f"[DEBUG] Log written to {LOG_FILE}")
    return {"status": "ok"}
