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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"""Database configuration and connection management."""

import os
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, Generator
from uuid import uuid4

from sqlalchemy import create_engine, event, text
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, declarative_base, sessionmaker

from src.utils.env import env_bool, env_int


def _resolve_data_dir() -> Path:
    """Resolve a writable data directory across desktop/server environments."""
    candidates = []

    env_dir = str(os.getenv("AI_TESTER_DATA_DIR", "") or "").strip()
    if env_dir:
        candidates.append(Path(env_dir).expanduser())

    candidates.append(Path("./data"))
    candidates.append(Path.home() / ".ai-testing-platform" / "data")
    candidates.append(Path(tempfile.gettempdir()) / "ai-testing-platform-data")

    for directory in candidates:
        try:
            directory.mkdir(parents=True, exist_ok=True)
            return directory
        except Exception:
            continue

    # Last safety net (in-memory-ish temp location).
    fallback = Path(tempfile.mkdtemp(prefix="ai-tester-data-"))
    return fallback


# Creazione directory data con fallback sicuro
DATA_DIR = _resolve_data_dir()

# Base per i modelli SQLAlchemy
Base = declarative_base()


class Database:
    """Gestione database con SQLAlchemy."""

    def __init__(self, database_url: str = None):
        self.database_url = database_url or os.getenv(
            "DATABASE_URL", f"sqlite:///{DATA_DIR}/ai_tester.db"
        )

        # Configurazione engine
        connect_args: Dict[str, Any] = {}
        engine_kwargs: Dict[str, Any] = {
            "echo": env_bool("DEBUG", False),
            "pool_pre_ping": env_bool("DB_POOL_PRE_PING", True),
        }
        if self.database_url.startswith("sqlite"):
            # SQLite uses a single-connection pool; the size kwargs would
            # conflict (NullPool by default for non-file URLs). Keep it simple.
            connect_args["check_same_thread"] = False
        else:
            # Postgres / MySQL / etc. — let the operator tune the pool from env.
            # Defaults are conservative for Render's free/starter tier where
            # connection limits on the upstream DB are tight.
            engine_kwargs.update(
                pool_size=env_int("DB_POOL_SIZE", 5),
                max_overflow=env_int("DB_MAX_OVERFLOW", 10),
                pool_recycle=env_int("DB_POOL_RECYCLE_SECONDS", 300),
                pool_timeout=env_int("DB_POOL_TIMEOUT_SECONDS", 30),
            )

        self.engine = create_engine(
            self.database_url,
            connect_args=connect_args,
            **engine_kwargs,
        )

        # Session factory
        self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)

        # Setup per SQLite
        if self.database_url.startswith("sqlite"):
            self._setup_sqlite()

    def _setup_sqlite(self):
        """Setup specifico per SQLite (foreign keys, etc)."""

        @event.listens_for(Engine, "connect")
        def set_sqlite_pragma(dbapi_conn, connection_record):
            cursor = dbapi_conn.cursor()
            cursor.execute("PRAGMA foreign_keys=ON")
            cursor.close()

    def create_tables(self):
        """Crea tutte le tabelle."""
        # Importa qui per evitare circular imports
        Base.metadata.create_all(bind=self.engine)
        self._apply_compatibility_migrations()

    def drop_tables(self):
        """Drop tutte le tabelle (attenzione!)."""
        Base.metadata.drop_all(bind=self.engine)

    def _apply_compatibility_migrations(self):
        """
        Apply non-destructive schema compatibility migrations.

        DB engines do not auto-alter existing tables when SQLAlchemy models add
        new columns, so older schemas can break API queries at runtime.
        """
        required_columns = {
            "bots": {
                "workspace_id": "VARCHAR(36)",
                "deterministic_fallbacks": "JSON",
                "knowledge_boundary_content": "TEXT",
                "knowledge_boundary_updated_at": "TIMESTAMP",
            },
            "personas": {
                "workspace_id": "VARCHAR(36)",
            },
            "scenarios": {
                "workspace_id": "VARCHAR(36)",
                "mode": "VARCHAR(32) DEFAULT 'deterministic'",
                "followup_policy": "VARCHAR(32) DEFAULT 'limited'",
                "followup_max_turns": "INTEGER DEFAULT 1",
                "seed_questions": "JSON",
                "supports_context": "BOOLEAN DEFAULT TRUE",
            },
            "rag_documents": {
                "workspace_id": "VARCHAR(36)",
            },
            "bot_versions": {
                "workspace_id": "VARCHAR(36)",
            },
            "test_sessions": {
                "workspace_id": "VARCHAR(36)",
                "max_messages": "INTEGER",
                "max_turns": "INTEGER",
                "min_turns": "INTEGER DEFAULT 1",
                "critical_questions": "JSON",
                "termination_policy": "JSON",
                "messages_sent": "INTEGER DEFAULT 0",
                "knowledge_snapshot_id": "VARCHAR(36)",
                "memory_status": "JSON",
            },
            "test_results": {
                "workspace_id": "VARCHAR(36)",
                "scenario_results": "JSON",
                "termination_reason": "VARCHAR(128)",
            },
            "interactions": {
                "correctness_label": "VARCHAR(24)",
                "correctness_reasoning": "TEXT",
                "claims_json": "JSON",
                "evidence_pack_json": "JSON",
                "human_override_label": "VARCHAR(24)",
                "human_override_intent_label": "VARCHAR(24)",
                "human_override_reason": "TEXT",
                "human_override_reviewer_id": "VARCHAR(255)",
                "human_override_at": "TIMESTAMP",
                "retry_count": "INTEGER",
            },
            "bug_tickets": {
                "turn_id": "VARCHAR(36)",
                "interaction_turn_number": "INTEGER",
                "expected_behavior": "TEXT",
                "external_parent_id": "VARCHAR(64)",
                "external_category_id": "VARCHAR(64)",
                "external_id": "VARCHAR(64)",
                "external_url": "VARCHAR(500)",
                "external_project_identifier": "VARCHAR(128)",
                "sync_status": "VARCHAR(16) DEFAULT 'pending'",
                "sync_error": "TEXT",
                "sync_attempts": "INTEGER DEFAULT 0",
                "synced_at": "TIMESTAMP",
            },
        }

        # Extend test_sessions with verdict columns.
        required_columns["test_sessions"].update(
            {
                "verdict_label": "VARCHAR(24)",
                "verdict_p_hat": "FLOAT",
                "verdict_lower_bound": "FLOAT",
                "verdict_upper_bound": "FLOAT",
                "verdict_threshold": "FLOAT",
                "verdict_n": "INTEGER",
            }
        )

        with self.engine.begin() as conn:
            if self.database_url.startswith("sqlite"):
                for table_name, columns in required_columns.items():
                    existing_tables = {
                        row[0]
                        for row in conn.execute(
                            text("SELECT name FROM sqlite_master WHERE type='table'")
                        ).fetchall()
                    }
                    if table_name not in existing_tables:
                        continue
                    existing = {
                        row[1]
                        for row in conn.execute(text(f"PRAGMA table_info({table_name})")).fetchall()
                    }
                    for column_name, column_def in columns.items():
                        if column_name in existing:
                            continue
                        conn.execute(
                            text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_def}")
                        )

                # Indexes added after initial schema (compat for existing DBs).
                try:
                    conn.execute(
                        text(
                            "CREATE INDEX IF NOT EXISTS idx_bug_tickets_sync_status "
                            "ON bug_tickets(sync_status)"
                        )
                    )
                except Exception:
                    pass

                # Ensure one default workspace exists and backfill legacy rows.
                conn.execute(
                    text(
                        """
                        INSERT OR IGNORE INTO workspaces (id, name, description, is_active, created_at, updated_at, created_by)
                        VALUES ('00000000-0000-0000-0000-000000000001', 'default-migrated', 'Auto-migrated default workspace', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'system')
                        """
                    )
                )
                for table_name in (
                    "bots",
                    "personas",
                    "scenarios",
                    "rag_documents",
                    "bot_versions",
                    "test_sessions",
                    "test_results",
                ):
                    try:
                        conn.execute(
                            text(
                                f"""
                                UPDATE {table_name}
                                SET workspace_id = '00000000-0000-0000-0000-000000000001'
                                WHERE workspace_id IS NULL OR workspace_id = ''
                                """
                            )
                        )
                    except Exception:
                        continue

                # Ensure max_turns mirrors legacy max_messages when needed.
                try:
                    conn.execute(
                        text(
                            """
                            UPDATE test_sessions
                            SET max_turns = max_messages
                            WHERE max_turns IS NULL AND max_messages IS NOT NULL
                            """
                        )
                    )
                except Exception:
                    pass

                # Backfill memberships from legacy created_by fields.
                legacy_users = set()
                for table_name in ("bots", "personas", "scenarios", "test_sessions"):
                    try:
                        rows = conn.execute(
                            text(
                                f"""
                                SELECT DISTINCT created_by
                                FROM {table_name}
                                WHERE created_by IS NOT NULL
                                AND TRIM(created_by) <> ''
                                """
                            )
                        ).fetchall()
                        for row in rows:
                            if row and row[0]:
                                legacy_users.add(str(row[0]))
                    except Exception:
                        continue
                for user_id in legacy_users:
                    conn.execute(
                        text(
                            """
                            INSERT OR IGNORE INTO workspace_members (id, workspace_id, user_id, role, created_at, updated_at)
                            VALUES (:id, '00000000-0000-0000-0000-000000000001', :user_id, 'workspace_owner', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
                            """
                        ),
                        {"id": str(uuid4()), "user_id": user_id},
                    )
                return

            # PostgreSQL / Supabase path
            for table_name, columns in required_columns.items():
                existing = {
                    row[0]
                    for row in conn.execute(
                        text(
                            """
                            SELECT column_name
                            FROM information_schema.columns
                            WHERE table_name = :table_name
                            AND table_schema = ANY(current_schemas(false))
                            """
                        ),
                        {"table_name": table_name},
                    ).fetchall()
                }
                for column_name, column_def in columns.items():
                    if column_name in existing:
                        continue
                    conn.execute(
                        text(
                            f"ALTER TABLE {table_name} ADD COLUMN IF NOT EXISTS {column_name} {column_def}"
                        )
                    )

            # Indexes added after initial schema (compat for existing DBs).
            try:
                conn.execute(
                    text(
                        "CREATE INDEX IF NOT EXISTS idx_bug_tickets_sync_status "
                        "ON bug_tickets(sync_status)"
                    )
                )
            except Exception:
                pass

            conn.execute(
                text(
                    """
                    INSERT INTO workspaces (id, name, description, is_active, created_at, updated_at, created_by)
                    VALUES ('00000000-0000-0000-0000-000000000001', 'default-migrated', 'Auto-migrated default workspace', TRUE, NOW(), NOW(), 'system')
                    ON CONFLICT (id) DO NOTHING
                    """
                )
            )
            for table_name in (
                "bots",
                "personas",
                "scenarios",
                "rag_documents",
                "bot_versions",
                "test_sessions",
                "test_results",
            ):
                try:
                    conn.execute(
                        text(
                            f"""
                            UPDATE {table_name}
                            SET workspace_id = '00000000-0000-0000-0000-000000000001'
                            WHERE workspace_id IS NULL OR workspace_id = ''
                            """
                        )
                    )
                except Exception:
                    continue
            try:
                conn.execute(
                    text(
                        """
                        UPDATE test_sessions
                        SET max_turns = max_messages
                        WHERE max_turns IS NULL AND max_messages IS NOT NULL
                        """
                    )
                )
            except Exception:
                pass

            legacy_users = set()
            for table_name in ("bots", "personas", "scenarios", "test_sessions"):
                try:
                    rows = conn.execute(
                        text(
                            f"""
                            SELECT DISTINCT created_by
                            FROM {table_name}
                            WHERE created_by IS NOT NULL
                            AND BTRIM(created_by) <> ''
                            """
                        )
                    ).fetchall()
                    for row in rows:
                        if row and row[0]:
                            legacy_users.add(str(row[0]))
                except Exception:
                    continue

            for user_id in legacy_users:
                conn.execute(
                    text(
                        """
                        INSERT INTO workspace_members (id, workspace_id, user_id, role, created_at, updated_at)
                        VALUES (:id, '00000000-0000-0000-0000-000000000001', :user_id, 'workspace_owner', NOW(), NOW())
                        ON CONFLICT (workspace_id, user_id) DO NOTHING
                        """
                    ),
                    {"id": str(uuid4()), "user_id": user_id},
                )

    @contextmanager
    def get_session(self) -> Generator[Session, None, None]:
        """Context manager per sessioni DB."""
        session = self.SessionLocal()
        try:
            yield session
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()

    def close(self):
        """Chiude connessione."""
        self.engine.dispose()


# Singleton instance
_db_instance: Database = None


def get_db() -> Database:
    """Restituisce singleton instance del database."""
    global _db_instance
    if _db_instance is None:
        _db_instance = Database()
    return _db_instance


def init_db():
    """Inizializza database (da chiamare all'avvio)."""
    db = get_db()
    db.create_tables()
    return db