Spaces:
Paused

File size: 11,184 Bytes
07612e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
YAZ Care Platform CLI
Command-line interface for healthcare analytics
"""

import argparse
import asyncio
import json
import sys
from pathlib import Path
from typing import Dict, List, Optional

# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent / "src"))

try:
    # Try to import the required modules
    from core.api_client import APIClient
    API_AVAILABLE = True
except ImportError:
    # Fallback mode without API client
    API_AVAILABLE = False
    print("⚠️  API client not available. Running in demo mode.")


class YazCareCLI:
    """Command-line interface for YAZ Care Platform"""
    
    def __init__(self):
        if API_AVAILABLE:
            self.client = APIClient()
        else:
            self.client = None
    
    def print_banner(self):
        """Print YAZ Care banner"""
        banner = """
╔══════════════════════════════════════════════════════════════╗
║                      YAZ Care Platform                      ║
║              Healthcare Analytics & Management               ║
╚══════════════════════════════════════════════════════════════╝
        """
        print(banner)
    
    def print_table(self, data: List[Dict], headers: Optional[List[str]] = None):
        """Print data as a formatted table"""
        if not data:
            print("No data available")
            return
        
        if not headers:
            headers = list(data[0].keys()) if data else []
        
        # Calculate column widths
        widths = {}
        for header in headers:
            widths[header] = max(len(str(header)), 
                               max(len(str(row.get(header, ""))) for row in data))
        
        # Print header
        header_row = " | ".join(f"{header:<{widths[header]}}" for header in headers)
        print(header_row)
        print("-" * len(header_row))
        
        # Print data rows
        for row in data:
            data_row = " | ".join(f"{str(row.get(header, '')):<{widths[header]}}" for header in headers)
            print(data_row)
    
    def list_studies(self):
        """List all studies"""
        print("\n📊 Studies:")
        print("-" * 50)
        
        try:
            # Mock data for CLI demo
            studies = [
                {"ID": "1", "Name": "Oujda_2025_Gastric_ADK_CI", "Status": "Active", "Patients": 127},
                {"ID": "2", "Name": "Casablanca_D2_Validation", "Status": "Completed", "Patients": 89},
                {"ID": "3", "Name": "FLOT_Dosing_Analysis", "Status": "In Progress", "Patients": 156}
            ]
            
            self.print_table(studies)
        except Exception as e:
            print(f"Error fetching studies: {e}")
    
    def import_study(self, file_path: str, study_name: str):
        """Import study data from file"""
        print(f"\n📁 Importing study: {study_name}")
        print(f"File: {file_path}")
        print("-" * 50)
        
        try:
            if not Path(file_path).exists():
                print(f"❌ File not found: {file_path}")
                return
            
            # Mock import process
            print("🔄 Processing file...")
            print("✅ Validating data format...")
            print("✅ Importing patient records...")
            print("✅ Running quality checks...")
            print(f"✅ Study '{study_name}' imported successfully!")
            print(f"   - Records processed: 127")
            print(f"   - Validation errors: 0")
            print(f"   - Warnings: 3")
            
        except Exception as e:
            print(f"❌ Import failed: {e}")
    
    def run_analysis(self, study_id: str, analysis_type: str = "survival"):
        """Run analysis on study data"""
        print(f"\n📈 Running {analysis_type} analysis")
        print(f"Study ID: {study_id}")
        print("-" * 50)
        
        try:
            print("🔄 Loading study data...")
            print("🔄 Running statistical analysis...")
            print("🔄 Generating results...")
            
            # Mock analysis results
            results = {
                "study_id": study_id,
                "analysis_type": analysis_type,
                "total_patients": 127,
                "survival_rate": "94.2%",
                "median_follow_up": "18.3 months",
                "complications_rate": "5.8%"
            }
            
            print("✅ Analysis completed!")
            print("\n📋 Results:")
            for key, value in results.items():
                print(f"   {key.replace('_', ' ').title()}: {value}")
                
        except Exception as e:
            print(f"❌ Analysis failed: {e}")
    
    def validate_cohort(self, study_id: str):
        """Validate study cohort"""
        print(f"\n🔍 Validating cohort for study: {study_id}")
        print("-" * 50)
        
        try:
            print("🔄 Checking data completeness...")
            print("🔄 Validating D2 compliance...")
            print("🔄 Analyzing FLOT dosing intensity...")
            
            # Mock validation results
            validation = {
                "total_patients": 127,
                "complete_records": 124,
                "d2_compliant": 119,
                "missing_data": 3,
                "quality_score": "94.5%"
            }
            
            print("✅ Validation completed!")
            print("\n📋 Validation Summary:")
            for key, value in validation.items():
                print(f"   {key.replace('_', ' ').title()}: {value}")
            
            # Print warnings if any
            if validation["missing_data"] > 0:
                print(f"\n⚠️  {validation['missing_data']} patients have missing data fields")
                
        except Exception as e:
            print(f"❌ Validation failed: {e}")
    
    def show_status(self):
        """Show platform status"""
        print("\n📊 Platform Status:")
        print("-" * 50)
        
        try:
            status = {
                "🟢 System": "Operational",
                "📚 Active Studies": "3",
                "👥 Total Patients": "372",
                "⚡ Processing Queue": "Empty",
                "💾 Storage Used": "1.2 GB",
                "🔄 Last Backup": "2 hours ago"
            }
            
            for key, value in status.items():
                print(f"{key}: {value}")
                
        except Exception as e:
            print(f"❌ Status check failed: {e}")
    
    def run_interactive(self):
        """Run interactive CLI mode"""
        self.print_banner()
        print("🚀 Welcome to YAZ Care Platform CLI")
        print("Type 'help' for available commands or 'quit' to exit\n")
        
        commands = {
            "studies": "List all studies",
            "status": "Show platform status", 
            "import": "Import study data (usage: import <file> <study_name>)",
            "analyze": "Run analysis (usage: analyze <study_id> [analysis_type])",
            "validate": "Validate cohort (usage: validate <study_id>)",
            "help": "Show this help message",
            "quit": "Exit the CLI"
        }
        
        while True:
            try:
                cmd = input("yaz-care> ").strip().split()
                
                if not cmd:
                    continue
                
                command = cmd[0].lower()
                
                if command == "quit":
                    print("👋 Goodbye!")
                    break
                elif command == "help":
                    print("\n📖 Available Commands:")
                    for cmd_name, desc in commands.items():
                        print(f"  {cmd_name:<10} - {desc}")
                    print()
                elif command == "studies":
                    self.list_studies()
                elif command == "status":
                    self.show_status()
                elif command == "import" and len(cmd) >= 3:
                    file_path = cmd[1]
                    study_name = " ".join(cmd[2:])
                    self.import_study(file_path, study_name)
                elif command == "analyze" and len(cmd) >= 2:
                    study_id = cmd[1]
                    analysis_type = cmd[2] if len(cmd) > 2 else "survival"
                    self.run_analysis(study_id, analysis_type)
                elif command == "validate" and len(cmd) >= 2:
                    study_id = cmd[1]
                    self.validate_cohort(study_id)
                else:
                    print(f"❌ Unknown command: {command}")
                    print("Type 'help' for available commands")
                
            except KeyboardInterrupt:
                print("\n👋 Goodbye!")
                break
            except Exception as e:
                print(f"❌ Error: {e}")


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="YAZ Care Platform CLI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s                                    # Interactive mode
  %(prog)s studies                           # List studies
  %(prog)s import data.csv "Study Name"      # Import study
  %(prog)s analyze study_1 survival         # Run analysis
  %(prog)s validate study_1                 # Validate cohort
  %(prog)s status                           # Show status
        """
    )
    
    parser.add_argument("command", nargs="?", help="Command to execute")
    parser.add_argument("args", nargs="*", help="Command arguments")
    parser.add_argument("--version", action="version", version="YAZ Care Platform CLI v1.0.0")
    
    args = parser.parse_args()
    cli = YazCareCLI()
    
    if not args.command:
        # Interactive mode
        cli.run_interactive()
    else:
        # Single command mode
        command = args.command.lower()
        
        if command == "studies":
            self.list_studies()
        elif command == "status":
            self.show_status()
        elif command == "import" and len(args.args) >= 2:
            file_path = args.args[0]
            study_name = " ".join(args.args[1:])
            self.import_study(file_path, study_name)
        elif command == "analyze" and len(args.args) >= 1:
            study_id = args.args[0]
            analysis_type = args.args[1] if len(args.args) > 1 else "survival"
            self.run_analysis(study_id, analysis_type)
        elif command == "validate" and len(args.args) >= 1:
            study_id = args.args[0]
            self.validate_cohort(study_id)
        else:
            cli.print_banner()
            print(f"❌ Unknown command: {command}")
            print("Use --help for usage information")


if __name__ == "__main__":
    main()