File size: 11,323 Bytes
b6145cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a34989b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
# services/data/artifacts.py
"""
Data Artifacts Service

This module provides file-based artifact generation and management for
operational data. It handles saving structured data to various formats
and managing artifact lifecycle.

Purpose:
- Save operational data to files (JSON, CSV, etc.)
- Generate standardized filenames with timestamps and metadata
- Manage artifact storage locations and cleanup
- Provide consistent artifact metadata

Design Principles:
- Configurable output directories
- Timestamped filenames for traceability
- Metadata embedding in saved files
- Error handling for storage failures
- Support for multiple output formats

Dependencies:
- json: For JSON serialization
- os: For file system operations
- datetime: For timestamp generation

Called by:
- tools/*/adapter.py: Main tool adapters for data persistence
- services/reports/*: Report generation services
- Direct usage: Emergency management data export

Security Notes:
- Validates output paths to prevent directory traversal
- Uses safe filename generation
- Handles permissions and disk space gracefully

TODO: implement permanent configurable storage with retention policies
"""

import json
import os
import csv
from typing import Dict, Any, List, Optional, Union
from datetime import datetime
from pathlib import Path


class ArtifactConfig:
    """Configuration for artifact generation"""
    
    def __init__(
        self,
        base_dir: str = "/tmp/omirl_data",
        include_timestamp: bool = True,
        include_metadata: bool = True,
        filename_format: str = "{prefix}_{timestamp}{suffix}.{extension}"
    ):
        self.base_dir = base_dir
        self.include_timestamp = include_timestamp
        self.include_metadata = include_metadata
        self.filename_format = filename_format


class ArtifactManager:
    """
    Manages data artifact creation and storage
    
    This class provides a standardized way to save operational data
    to various file formats with consistent naming and metadata.
    """
    
    def __init__(self, config: Optional[ArtifactConfig] = None):
        self.config = config or ArtifactConfig()
        self._ensure_base_directory()
    
    def _ensure_base_directory(self):
        """Create base directory if it doesn't exist"""
        try:
            os.makedirs(self.config.base_dir, exist_ok=True)
        except Exception as e:
            print(f"⚠️  Warning: Could not create base directory {self.config.base_dir}: {e}")
    
    async def save_station_data(
        self,
        stations: List[Dict[str, Any]],
        filters: Dict[str, Any] = None,
        source: str = "OMIRL",
        format: str = "json"
    ) -> Optional[str]:
        """
        Save weather station data to file
        
        Args:
            stations: List of station data dictionaries
            filters: Applied filters for filename generation
            source: Data source name
            format: Output format ("json" or "csv")
            
        Returns:
            Filepath of saved file, or None if failed
        """
        try:
            # Generate filename
            filename = self._generate_filename(
                prefix="stazioni",
                filters=filters,
                extension=format
            )
            
            filepath = os.path.join(self.config.base_dir, filename)
            
            # Prepare data with metadata
            if format == "json":
                return await self._save_as_json(stations, filepath, filters, source)
            elif format == "csv":
                return await self._save_as_csv(stations, filepath, filters, source)
            else:
                print(f"⚠️  Unsupported format: {format}")
                return None
                
        except Exception as e:
            print(f"⚠️  Failed to save station data: {e}")
            return None
    
    async def save_generic_data(
        self,
        data: Union[List[Dict], Dict[str, Any]],
        prefix: str = "data",
        filters: Dict[str, Any] = None,
        source: str = "Unknown",
        format: str = "json"
    ) -> Optional[str]:
        """
        Save generic operational data to file
        
        Args:
            data: Data to save (list of dicts or single dict)
            prefix: Filename prefix
            filters: Applied filters for filename generation
            source: Data source name
            format: Output format
            
        Returns:
            Filepath of saved file, or None if failed
        """
        try:
            filename = self._generate_filename(
                prefix=prefix,
                filters=filters,
                extension=format
            )
            
            filepath = os.path.join(self.config.base_dir, filename)
            
            if format == "json":
                return await self._save_generic_json(data, filepath, filters, source)
            else:
                print(f"⚠️  Unsupported format for generic data: {format}")
                return None
                
        except Exception as e:
            print(f"⚠️  Failed to save generic data: {e}")
            return None
    
    def _generate_filename(
        self,
        prefix: str,
        filters: Dict[str, Any] = None,
        extension: str = "json"
    ) -> str:
        """Generate standardized filename with timestamp and filters"""
        
        # Base components
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") if self.config.include_timestamp else ""
        
        # Add filter-based suffix
        suffix = ""
        if filters:
            filter_parts = []
            for key, value in filters.items():
                if value:
                    # Clean value for filename
                    clean_value = str(value).lower().replace(" ", "_").replace("'", "")
                    filter_parts.append(f"{key}_{clean_value}")
            
            if filter_parts:
                suffix = "_" + "_".join(filter_parts[:3])  # Limit to 3 filters for filename length
        
        # Format filename
        return self.config.filename_format.format(
            prefix=prefix,
            timestamp=timestamp,
            suffix=suffix,
            extension=extension
        )
    
    async def _save_as_json(
        self,
        stations: List[Dict[str, Any]],
        filepath: str,
        filters: Dict[str, Any],
        source: str
    ) -> str:
        """Save station data as JSON with metadata"""
        
        data_to_save = {
            "metadata": {
                "extraction_timestamp": datetime.now().isoformat(),
                "source": source,
                "filters_applied": filters or {},
                "station_count": len(stations),
                "format_version": "1.0"
            },
            "stations": stations
        } if self.config.include_metadata else stations
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data_to_save, f, ensure_ascii=False, indent=2)
        
        print(f"💾 Station data saved to: {filepath}")
        return filepath
    
    async def _save_as_csv(
        self,
        stations: List[Dict[str, Any]],
        filepath: str,
        filters: Dict[str, Any],
        source: str
    ) -> str:
        """Save station data as CSV"""
        
        if not stations:
            # Create empty CSV with headers
            with open(filepath, 'w', encoding='utf-8', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(["Nome", "Codice", "Comune", "Provincia"])
        else:
            # Get headers from first station
            headers = list(stations[0].keys())
            
            with open(filepath, 'w', encoding='utf-8', newline='') as f:
                writer = csv.DictWriter(f, fieldnames=headers)
                writer.writeheader()
                
                for station in stations:
                    writer.writerow(station)
        
        print(f"💾 Station data saved to CSV: {filepath}")
        return filepath
    
    async def _save_generic_json(
        self,
        data: Union[List[Dict], Dict[str, Any]],
        filepath: str,
        filters: Dict[str, Any],
        source: str
    ) -> str:
        """Save generic data as JSON with metadata"""
        
        data_to_save = {
            "metadata": {
                "extraction_timestamp": datetime.now().isoformat(),
                "source": source,
                "filters_applied": filters or {},
                "record_count": len(data) if isinstance(data, list) else 1,
                "format_version": "1.0"
            },
            "data": data
        } if self.config.include_metadata else data
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data_to_save, f, ensure_ascii=False, indent=2)
        
        print(f"💾 Data saved to: {filepath}")
        return filepath


# Factory function for common configurations
def create_artifact_manager(
    base_dir: str = "/tmp/omirl_data",
    include_metadata: bool = True
) -> ArtifactManager:
    """
    Create an artifact manager with custom configuration
    
    Args:
        base_dir: Base directory for saving artifacts
        include_metadata: Whether to include metadata in saved files
        
    Returns:
        Configured ArtifactManager instance
    """
    config = ArtifactConfig(
        base_dir=base_dir,
        include_metadata=include_metadata
    )
    
    return ArtifactManager(config)


# Convenience functions for common use cases
async def save_omirl_stations(
    stations: List[Dict[str, Any]],
    filters: Dict[str, Any] = None,
    format: str = "json",
    base_dir: str = "/tmp/omirl_data"
) -> Optional[str]:
    """
    Quick function to save OMIRL station data
    
    This is a convenience function that creates an artifact manager
    and saves station data in one call.
    """
    manager = create_artifact_manager(base_dir=base_dir)
    return await manager.save_station_data(
        stations=stations,
        filters=filters,
        source="OMIRL Valori Stazioni",
        format=format
    )

async def save_omirl_precipitation_data(
    precipitation_data: Dict[str, List[Dict[str, Any]]],
    filters: Dict[str, Any] = None,
    format: str = "json",
    base_dir: str = "/tmp/omirl_data"
) -> Optional[str]:
    """
    Quick function to save OMIRL precipitation data
    
    This is a convenience function that creates an artifact manager
    and saves precipitation data from both zona d'allerta and province tables.
    """
    manager = create_artifact_manager(base_dir=base_dir)
    
    # Flatten the precipitation data for consistent saving
    # Include metadata about which table each record came from
    flattened_data = []
    
    for table_type in ["zona_allerta", "province"]:
        for record in precipitation_data.get(table_type, []):
            record_with_type = {**record, "table_type": table_type}
            flattened_data.append(record_with_type)
    
    return await manager.save_station_data(
        stations=flattened_data,
        filters=filters,
        source="OMIRL Massimi Precipitazione",
        format=format
    )