File size: 3,335 Bytes
514b626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""Context database and management system"""

import json
from pathlib import Path
from typing import Dict, List, Optional
from .models import EnvironmentalContext


class ContextDatabase:
    """Database for managing environmental contexts"""

    def __init__(self, contexts_dir: Optional[Path] = None):
        """
        Initialize context database

        Args:
            contexts_dir: Directory containing context JSON files.
                         Defaults to data/contexts relative to project root.
        """
        if contexts_dir is None:
            # Default to data/contexts from project root
            project_root = Path(__file__).parent.parent.parent
            contexts_dir = project_root / "data" / "contexts"

        self.contexts_dir = Path(contexts_dir)
        self.contexts: Dict[str, EnvironmentalContext] = {}
        self._load_contexts()

    def _load_contexts(self) -> None:
        """Load all context JSON files from the contexts directory"""
        if not self.contexts_dir.exists():
            print(f"Warning: Contexts directory not found: {self.contexts_dir}")
            print("Creating empty contexts directory...")
            self.contexts_dir.mkdir(parents=True, exist_ok=True)
            return

        json_files = list(self.contexts_dir.glob("*.json"))
        if not json_files:
            print(f"Warning: No context JSON files found in {self.contexts_dir}")
            return

        for json_file in json_files:
            try:
                with open(json_file, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    context = EnvironmentalContext(**data)
                    self.contexts[context.context_id] = context
            except Exception as e:
                print(f"Warning: Failed to load {json_file}: {e}")

        print(f"Loaded {len(self.contexts)} environmental contexts")

    def get_context(self, context_id: str) -> Optional[EnvironmentalContext]:
        """
        Retrieve a context by ID

        Args:
            context_id: Unique context identifier

        Returns:
            EnvironmentalContext object if found, None otherwise
        """
        return self.contexts.get(context_id)

    def get_all_contexts(self) -> List[EnvironmentalContext]:
        """
        Get all loaded contexts

        Returns:
            List of all EnvironmentalContext objects
        """
        return list(self.contexts.values())

    def list_context_ids(self) -> List[str]:
        """
        Get list of all context IDs

        Returns:
            List of context ID strings
        """
        return list(self.contexts.keys())

    def get_default_context(self) -> Optional[EnvironmentalContext]:
        """
        Get a default context (first available)

        Returns:
            First EnvironmentalContext or None if none exist
        """
        if self.contexts:
            return list(self.contexts.values())[0]
        return None


def load_context_from_file(filepath: Path) -> EnvironmentalContext:
    """
    Load a single context from a JSON file

    Args:
        filepath: Path to JSON file

    Returns:
        EnvironmentalContext object
    """
    with open(filepath, "r", encoding="utf-8") as f:
        data = json.load(f)
        return EnvironmentalContext(**data)