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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
#!/usr/bin/env python3
"""
Tool Generator - Create standardized tool structure

This script generates a complete tool structure with:
- Models (SQLModel with TenantMixin, TimestampMixin)
- Schemas (Pydantic with OpenAPI examples)
- Routes (FastAPI with RBAC, rate limiting)
- Services (Business logic with BaseService inheritance)
- Adapters (Event-driven wrappers)
- Events (Domain event definitions)
- Tests (85%+ coverage scaffolding)

Usage:
    python scripts/generators/create_tool.py \\
        --name mednote \\
        --display-name "MedNote (Clinical Documentation)" \\
        --category clinical \\
        --standards "HL7 FHIR,21 CFR Part 11" \\
        --description "Electronic clinical documentation"

Author: Platform Architecture Team
Date: December 28, 2025
Version: 2.0
"""

import os
import argparse
from pathlib import Path
from datetime import datetime
from typing import List


# ============================================================================
# TEMPLATES
# ============================================================================

INIT_TEMPLATE = '''"""
{display_name} Tool Module

Auto-generated on {timestamp}
Category: {category}
Standards: {standards}

This module provides {description}.
"""

from .routes import router
from .models import *
from .schemas import *

__all__ = ["router"]
'''

MODELS_TEMPLATE = '''"""
{display_name} - Domain Models

Clinical Context: {description}
Standards: {standards}
Performance: <100ms CRUD operations (p95)
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional, List
from uuid import UUID, uuid4

from sqlmodel import SQLModel, Field, Relationship
from sqlalchemy import String, Text, JSON
from sqlalchemy.dialects.postgresql import UUID as PGUUID

from core.database.mixins import TenantMixin, TimestampMixin, SoftDeleteMixin


class {entity_class}(TenantMixin, TimestampMixin, SoftDeleteMixin, table=True):
    """
    {entity_class} domain model
    
    Clinical Context:
        {description}
    
    Standards Compliance:
        {standards_list}
    
    Performance Targets:
        - CREATE: <100ms p95
        - READ: <50ms p95
        - UPDATE: <100ms p95
        - DELETE: <50ms p95 (soft delete)
    
    Security:
        - PHI: {phi_protected}
        - Audit: YES (all operations logged)
        - Encryption: AES-256 at rest
    
    Multi-Tenancy:
        - Schema: {name}.{table_name}
        - Isolation: STRICT (tenant_id required on all queries)
    """
    
    __tablename__ = "{table_name}"
    __table_args__ = {{
        "schema": "{name}",
        "comment": "{entity_class} records"
    }}
    
    # Primary Key
    id: UUID = Field(
        default_factory=uuid4,
        primary_key=True,
        sa_column_kwargs={{"type_": PGUUID(as_uuid=True)}},
        description="Unique identifier"
    )
    
    # Domain Fields (customize these)
    name: str = Field(
        ...,
        min_length=1,
        max_length=255,
        sa_column_kwargs={{"nullable": False}},
        description="{entity_class} name"
    )
    
    category: Optional[str] = Field(
        default=None,
        max_length=100,
        description="Category for grouping"
    )
    
    metadata_: dict = Field(
        default_factory=dict,
        sa_column=JSON,
        description="Flexible metadata storage"
    )
    
    def to_dict_safe(self) -> dict:
        """Convert to dictionary without PHI fields."""
        return {{
            "id": str(self.id),
            "tenant_id": str(self.tenant_id),
            "category": self.category,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat()
        }}
    
    def __repr__(self) -> str:
        """String representation without PHI."""
        return f"<{{self.__class__.__name__}}(id={{self.id}}, tenant={{self.tenant_id}})>"
'''

SCHEMAS_TEMPLATE = '''"""
{display_name} - API Schemas

Request/response models for {name} API endpoints.
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional, List
from uuid import UUID

from pydantic import BaseModel, Field, ConfigDict, field_validator


class Create{entity_class}Request(BaseModel):
    """
    Create {entity_class} request
    
    Clinical Context: {description}
    Standards: {standards}
    Performance: <200ms p95 (API endpoint)
    Security: RBAC role:CLINICIAN, audit_logging:yes, PHI:{phi_protected}
    """
    
    name: str = Field(
        ...,
        min_length=1,
        max_length=255,
        description="{entity_class} name with clinical context"
    )
    
    category: Optional[str] = Field(
        default=None,
        max_length=100,
        description="Category for grouping"
    )
    
    metadata_: dict = Field(
        default_factory=dict,
        description="Additional metadata"
    )
    
    model_config = ConfigDict(
        json_schema_extra={{
            "examples": [{{
                "name": "Example {entity_class}",
                "category": "clinical",
                "metadata_": {{"key": "value"}}
            }}]
        }}
    )


class {entity_class}Response(BaseModel):
    """
    {entity_class} response model
    """
    
    id: UUID
    tenant_id: UUID
    name: str
    category: Optional[str]
    metadata_: dict
    created_at: datetime
    updated_at: datetime
    created_by: Optional[UUID]
    updated_by: Optional[UUID]
    
    model_config = ConfigDict(from_attributes=True)


class Update{entity_class}Request(BaseModel):
    """
    Update {entity_class} request (partial update)
    """
    
    name: Optional[str] = Field(
        default=None,
        min_length=1,
        max_length=255
    )
    
    category: Optional[str] = Field(
        default=None,
        max_length=100
    )
    
    metadata_: Optional[dict] = None


class List{entity_class}Response(BaseModel):
    """
    Paginated list of {entity_class} records
    """
    
    items: List[{entity_class}Response]
    total: int
    page: int
    page_size: int
    has_more: bool
'''

ROUTES_TEMPLATE = '''"""
{display_name} - API Routes

RESTful API endpoints for {name} tool.
"""
from __future__ import annotations
from typing import Optional, List
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from core.database import get_db_session
from core.auth.dependencies import get_current_user, require_permission
from core.multitenancy.tenant import tenant_context
from core.models.user import User

from .schemas import (
    Create{entity_class}Request,
    {entity_class}Response,
    Update{entity_class}Request,
    List{entity_class}Response
)
from .services.{name}_service import {entity_class}Service


router = APIRouter(
    prefix="/api/v1/{name}",
    tags=["{display_name}"]
)


@router.post("/{plural}", response_model={entity_class}Response, status_code=201)
async def create_{name}(
    data: Create{entity_class}Request,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user),
    _: None = Depends(require_permission("{name}:{plural}:create"))
):
    """
    Create new {entity_class}
    
    Clinical Context: {description}
    Performance: <200ms p95
    Security: RBAC role:CLINICIAN
    """
    service = {entity_class}Service(session)
    result = await service.create(
        data=data.model_dump(),
        tenant_id=tenant_context.tenant_id,
        user_id=current_user.id
    )
    return result


@router.get("/{plural}", response_model=List{entity_class}Response)
async def list_{plural}(
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=1000, description="Items per page"),
    category: Optional[str] = Query(None, description="Filter by category"),
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user),
    _: None = Depends(require_permission("{name}:{plural}:read"))
):
    """
    List {entity_class} records with pagination
    
    Performance: <200ms p95 for 100 records
    """
    service = {entity_class}Service(session)
    result = await service.list_paginated(
        tenant_id=tenant_context.tenant_id,
        page=page,
        page_size=page_size,
        category=category
    )
    return result


@router.get("/{plural}/{{item_id}}", response_model={entity_class}Response)
async def get_{name}(
    item_id: UUID,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user),
    _: None = Depends(require_permission("{name}:{plural}:read"))
):
    """
    Get {entity_class} by ID
    
    Performance: <100ms p95
    """
    service = {entity_class}Service(session)
    result = await service.get_by_id(
        item_id=item_id,
        tenant_id=tenant_context.tenant_id
    )
    
    if not result:
        raise HTTPException(status_code=404, detail="{entity_class} not found")
    
    return result


@router.patch("/{plural}/{{item_id}}", response_model={entity_class}Response)
async def update_{name}(
    item_id: UUID,
    data: Update{entity_class}Request,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user),
    _: None = Depends(require_permission("{name}:{plural}:update"))
):
    """
    Update {entity_class}
    
    Performance: <200ms p95
    """
    service = {entity_class}Service(session)
    result = await service.update(
        item_id=item_id,
        data=data.model_dump(exclude_unset=True),
        tenant_id=tenant_context.tenant_id,
        user_id=current_user.id
    )
    
    if not result:
        raise HTTPException(status_code=404, detail="{entity_class} not found")
    
    return result


@router.delete("/{plural}/{{item_id}}", status_code=204)
async def delete_{name}(
    item_id: UUID,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user),
    _: None = Depends(require_permission("{name}:{plural}:delete"))
):
    """
    Delete {entity_class} (soft delete)
    
    Performance: <100ms p95
    """
    service = {entity_class}Service(session)
    await service.delete(
        item_id=item_id,
        tenant_id=tenant_context.tenant_id,
        user_id=current_user.id
    )
    
    return None
'''

SERVICE_TEMPLATE = '''"""
{display_name} - Business Logic Service

Core business logic for {name} tool.
"""
from __future__ import annotations
from typing import Optional, List, Dict, Any
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from sqlalchemy.sql import func
import structlog

from core.services.base import BaseService
from ..models import {entity_class}


logger = structlog.get_logger()


class {entity_class}Service(BaseService):
    """
    {entity_class} business logic service
    
    Inherits from BaseService:
    - Structured logging (OpenTelemetry)
    - Error handling (StandardErrorResponse)
    - Caching (4-tier strategy)
    - Tracing (distributed traces)
    - Metrics (Prometheus)
    """
    
    def __init__(self, session: AsyncSession):
        super().__init__(session)
        self.model = {entity_class}
    
    async def create(
        self,
        data: Dict[str, Any],
        tenant_id: UUID,
        user_id: UUID
    ) -> {entity_class}:
        """
        Create {entity_class}
        
        Performance: <100ms p95
        """
        entity = self.model(
            **data,
            tenant_id=tenant_id,
            created_by=user_id
        )
        
        self.session.add(entity)
        await self.session.commit()
        await self.session.refresh(entity)
        
        logger.info(
            "{name}_created",
            entity_id=str(entity.id),
            tenant_id=str(tenant_id),
            user_id=str(user_id)
        )
        
        return entity
    
    async def get_by_id(
        self,
        item_id: UUID,
        tenant_id: UUID
    ) -> Optional[{entity_class}]:
        """
        Get {entity_class} by ID
        
        Performance: <50ms p95
        """
        result = await self.session.execute(
            select(self.model).where(
                and_(
                    self.model.id == item_id,
                    self.model.tenant_id == tenant_id,
                    self.model.deleted_at.is_(None)  # Exclude soft-deleted
                )
            )
        )
        
        return result.scalars().first()
    
    async def list_paginated(
        self,
        tenant_id: UUID,
        page: int = 1,
        page_size: int = 50,
        category: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        List {entity_class} records with pagination
        
        Performance: <200ms p95 for 100 records
        """
        # Build query
        query = select(self.model).where(
            and_(
                self.model.tenant_id == tenant_id,
                self.model.deleted_at.is_(None)
            )
        )
        
        # Add filters
        if category:
            query = query.where(self.model.category == category)
        
        # Count total
        count_query = select(func.count()).select_from(query.subquery())
        total_result = await self.session.execute(count_query)
        total = total_result.scalar()
        
        # Paginate
        offset = (page - 1) * page_size
        query = query.offset(offset).limit(page_size)
        
        # Execute
        result = await self.session.execute(query)
        items = result.scalars().all()
        
        return {{
            "items": items,
            "total": total,
            "page": page,
            "page_size": page_size,
            "has_more": (offset + page_size) < total
        }}
    
    async def update(
        self,
        item_id: UUID,
        data: Dict[str, Any],
        tenant_id: UUID,
        user_id: UUID
    ) -> Optional[{entity_class}]:
        """
        Update {entity_class}
        
        Performance: <100ms p95
        """
        entity = await self.get_by_id(item_id, tenant_id)
        
        if not entity:
            return None
        
        # Update fields
        for field, value in data.items():
            if value is not None:
                setattr(entity, field, value)
        
        entity.updated_by = user_id
        
        await self.session.commit()
        await self.session.refresh(entity)
        
        logger.info(
            "{name}_updated",
            entity_id=str(entity.id),
            tenant_id=str(tenant_id),
            user_id=str(user_id)
        )
        
        return entity
    
    async def delete(
        self,
        item_id: UUID,
        tenant_id: UUID,
        user_id: UUID
    ) -> bool:
        """
        Soft delete {entity_class}
        
        Performance: <50ms p95
        """
        entity = await self.get_by_id(item_id, tenant_id)
        
        if not entity:
            return False
        
        # Soft delete
        from datetime import datetime
        entity.deleted_at = datetime.utcnow()
        entity.deleted_by = user_id
        
        await self.session.commit()
        
        logger.info(
            "{name}_deleted",
            entity_id=str(entity.id),
            tenant_id=str(tenant_id),
            user_id=str(user_id)
        )
        
        return True
'''


# ============================================================================
# GENERATOR LOGIC
# ============================================================================

def create_tool_structure(
    name: str,
    display_name: str,
    category: str,
    standards: List[str],
    description: str,
    phi_protected: bool = True
):
    """Create complete tool structure from templates."""
    
    # Paths
    base_path = Path(__file__).parent.parent.parent / "src" / "apps" / name
    services_path = base_path / "services"
    adapters_path = base_path / "adapters"
    events_path = base_path / "events"
    tests_path = Path(__file__).parent.parent.parent / "tests" / "apps" / name
    
    # Create directories
    base_path.mkdir(parents=True, exist_ok=True)
    services_path.mkdir(parents=True, exist_ok=True)
    adapters_path.mkdir(parents=True, exist_ok=True)
    events_path.mkdir(parents=True, exist_ok=True)
    tests_path.mkdir(parents=True, exist_ok=True)
    
    # Entity class name (PascalCase)
    entity_class = "".join(word.capitalize() for word in name.split("_"))
    table_name = f"{name}_records"
    plural = f"{name}s"
    
    # Format standards
    standards_str = ", ".join(standards)
    standards_list = "\n        ".join([f"- {s}: Compliance requirement" for s in standards])
    
    # Template context
    context = {
        "name": name,
        "display_name": display_name,
        "category": category,
        "standards": standards_str,
        "standards_list": standards_list,
        "description": description,
        "entity_class": entity_class,
        "table_name": table_name,
        "plural": plural,
        "phi_protected": "YES" if phi_protected else "NO",
        "timestamp": datetime.now().isoformat()
    }
    
    # Generate files
    files = {
        base_path / "__init__.py": INIT_TEMPLATE.format(**context),
        base_path / "models.py": MODELS_TEMPLATE.format(**context),
        base_path / "schemas.py": SCHEMAS_TEMPLATE.format(**context),
        base_path / "routes.py": ROUTES_TEMPLATE.format(**context),
        services_path / f"{name}_service.py": SERVICE_TEMPLATE.format(**context),
        services_path / "__init__.py": f"from .{name}_service import {entity_class}Service\n",
        adapters_path / "__init__.py": "# Event adapters\n",
        events_path / "__init__.py": "# Domain events\n",
        tests_path / "__init__.py": "# Tests\n",
    }
    
    for file_path, content in files.items():
        file_path.write_text(content)
        print(f"✅ Created: {file_path}")
    
    print(f"\n🎉 Tool '{name}' created successfully!")
    print(f"\n📋 Next steps:")
    print(f"1. Review generated files in: src/apps/{name}/")
    print(f"2. Customize domain models in: src/apps/{name}/models.py")
    print(f"3. Implement business logic in: src/apps/{name}/services/{name}_service.py")
    print(f"4. Create tests in: tests/apps/{name}/")
    print(f"5. Register tool: python scripts/governance/register_tool.py --slug {name}")
    print(f"6. Create migration: alembic revision --autogenerate -m 'Add {name} tool'")


def main():
    parser = argparse.ArgumentParser(description="Generate standardized tool structure")
    parser.add_argument("--name", required=True, help="Tool name (lowercase, underscores)")
    parser.add_argument("--display-name", required=True, help="Display name (e.g., 'MedNote (Clinical Documentation)')")
    parser.add_argument("--category", required=True, choices=["clinical", "financial", "logistics", "support", "platform"], help="Tool category")
    parser.add_argument("--standards", required=True, help="Comma-separated standards (e.g., 'HL7 FHIR,21 CFR Part 11')")
    parser.add_argument("--description", required=True, help="Tool description")
    parser.add_argument("--no-phi", action="store_true", help="Tool does not handle PHI")
    
    args = parser.parse_args()
    
    # Parse standards
    standards = [s.strip() for s in args.standards.split(",")]
    
    create_tool_structure(
        name=args.name,
        display_name=args.display_name,
        category=args.category,
        standards=standards,
        description=args.description,
        phi_protected=not args.no_phi
    )


if __name__ == "__main__":
    main()