File size: 2,597 Bytes
3177117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Smart Investigation Service Selector.

Automatically selects the correct investigation service implementation based on environment:
- HuggingFace Spaces: Uses REST API (HTTP/HTTPS)
- Local/VPS with PostgreSQL: Uses direct connection

This allows the same code to work in both environments without modification.
"""

import os
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src.services.investigation_service import InvestigationService

# Detect environment
def _is_huggingface_spaces() -> bool:
    """Detect if running on HuggingFace Spaces."""
    return os.getenv("SPACE_ID") is not None or os.getenv("SPACE_AUTHOR_NAME") is not None


def _has_supabase_rest_config() -> bool:
    """Check if Supabase REST API configuration is available."""
    return bool(os.getenv("SUPABASE_URL") and os.getenv("SUPABASE_SERVICE_ROLE_KEY"))


def _has_postgres_config() -> bool:
    """Check if PostgreSQL direct connection configuration is available."""
    return bool(os.getenv("DATABASE_URL") or os.getenv("SUPABASE_DB_URL"))


def get_investigation_service() -> "InvestigationService":
    """
    Get the appropriate investigation service for the current environment.

    Returns:
        Investigation service instance (REST API or direct PostgreSQL)
    """
    # Priority 1: HuggingFace Spaces MUST use REST API
    if _is_huggingface_spaces():
        if not _has_supabase_rest_config():
            raise RuntimeError(
                "HuggingFace Spaces detected but SUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY not configured. "
                "Add these to your Space secrets: https://huggingface.co/spaces/YOUR_SPACE/settings"
            )

        from src.services.investigation_service_supabase_rest import investigation_service_supabase_rest
        return investigation_service_supabase_rest

    # Priority 2: If REST API config available, prefer it (more portable)
    if _has_supabase_rest_config():
        from src.services.investigation_service_supabase_rest import investigation_service_supabase_rest
        return investigation_service_supabase_rest

    # Priority 3: If PostgreSQL config available, use direct connection
    if _has_postgres_config():
        from src.services.investigation_service_supabase import investigation_service_supabase
        return investigation_service_supabase

    # Fallback: Use in-memory service (no persistence)
    from src.services.investigation_service import investigation_service
    return investigation_service


# Global service instance - automatically selected
investigation_service = get_investigation_service()