"""
Simple trace logger with optional SQLAlchemy backend.

If DATABASE_URL is provided, use it; otherwise, keep an in-memory list
as a no-op tracer suitable for local execution.
"""

from __future__ import annotations

from typing import Any, Optional
import time
import os


class NoopTracer:
    def log(self, task_id: str, agent: str, event: str, payload: Any) -> None:  # noqa: D401
        pass


class TraceLogger:
    def __init__(self, db_url: Optional[str] = None):
        self.db_url = db_url or os.environ.get("DATABASE_URL")
        self._engine = None
        self._table = None
        if self.db_url:
            try:
                from sqlalchemy import create_engine, Table, Column, String, JSON, MetaData, Float  # type: ignore
                self._engine = create_engine(self.db_url)
                meta = MetaData()
                self._table = Table(
                    "traces",
                    meta,
                    Column("task_id", String),
                    Column("agent", String),
                    Column("event", String),
                    Column("payload", JSON),
                    Column("timestamp", Float),
                )
                meta.create_all(self._engine)
            except Exception:
                # Fall back to no-op if SQLAlchemy not available
                self.db_url = None

    def log(self, task_id: str, agent: str, event: str, payload: Any) -> None:
        if not self.db_url or not self._engine or not self._table:
            return
        try:
            with self._engine.begin() as conn:
                conn.execute(
                    self._table.insert().values(
                        task_id=task_id,
                        agent=agent,
                        event=event,
                        payload=payload,
                        timestamp=time.time(),
                    )
                )
        except Exception:
            # Swallow tracing errors in runtime
            return
