Spaces:
Paused

File size: 16,159 Bytes
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
2a99443
0743ddc
 
 
2a99443
0743ddc
 
 
2a99443
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
 
0743ddc
 
 
 
2a99443
0743ddc
 
 
 
2a99443
0743ddc
 
 
 
 
 
2a99443
 
 
 
 
 
0743ddc
 
 
 
 
2a99443
 
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
 
 
0743ddc
 
 
2a99443
0743ddc
2a99443
 
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
0743ddc
2a99443
0743ddc
2a99443
 
 
 
 
 
0743ddc
2a99443
 
0743ddc
2a99443
579285c
0743ddc
2a99443
 
 
 
0743ddc
2a99443
 
 
0743ddc
 
 
 
2a99443
0743ddc
 
 
 
2a99443
0743ddc
2a99443
0743ddc
 
 
 
2a99443
0743ddc
 
 
 
2a99443
 
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
 
2a99443
0743ddc
 
 
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
 
2a99443
 
0743ddc
 
 
 
 
 
 
 
2a99443
 
 
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
 
0743ddc
2a99443
 
 
 
 
 
0743ddc
2a99443
579285c
0743ddc
2a99443
587526a
 
2a99443
 
0743ddc
2a99443
 
0743ddc
 
2a99443
0743ddc
 
 
 
2a99443
0743ddc
 
 
 
2a99443
 
 
 
0743ddc
2a99443
 
 
0743ddc
 
2a99443
0743ddc
2a99443
 
 
 
 
 
 
 
 
 
 
0743ddc
2a99443
 
0743ddc
2a99443
 
0743ddc
2a99443
 
 
0743ddc
 
2a99443
0743ddc
 
 
 
2a99443
 
587526a
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
2a99443
 
0743ddc
2a99443
 
0743ddc
 
 
 
 
 
 
2a99443
0743ddc
 
 
2a99443
 
0743ddc
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
 
 
 
 
 
 
2a99443
0743ddc
 
2a99443
 
 
 
 
 
0743ddc
2a99443
 
 
 
 
0743ddc
2a99443
 
 
0743ddc
 
2a99443
 
 
0743ddc
2a99443
 
0743ddc
 
 
 
 
 
 
 
 
 
2a99443
 
 
 
 
 
0743ddc
2a99443
 
 
 
 
0743ddc
 
2a99443
 
 
 
 
 
 
 
0743ddc
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
YAZ Intelligence Registry — Creator Profiles & Intelligence Classification

Extends the Tool Registry to support the "Intelligence" concept:
- Intelligence = Domain expertise encoded as a composable tool
- Creator = Practitioner who builds intelligences from their practice
- Dual Licensing = Open (free) for learning/public, Licensed for profit

Architecture:
    Creator builds Intelligence → Publishes to Marketplace
    → Learners/Public get it free (AGPL)
    → Private entities license it (Commercial)
    → Anyone can fork it to build their own variant

First Creator: Dr. Anass Elamrani — Surgio (Surgical Intelligence)

Version: 1.0.0
Sprint: 40
Standards: AGPL-3.0 (open), Commercial (licensed)
"""

from datetime import UTC, datetime, timezone
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4

from pydantic import BaseModel, ConfigDict
from pydantic import Field as PydanticField
from sqlmodel import JSON, Column, Field, SQLModel

# ============================================================================
# ENUMERATIONS
# ============================================================================


class IntelligenceClass(str, Enum):
    """
    Classification of intelligence by domain expertise.

    An intelligence is a tool that encodes deep domain knowledge
    into structured workflows, protocols, and decision support.
    """

    SURGICAL = "surgical"  # Surgical workflows, OR management
    CLINICAL = "clinical"  # Patient care, diagnosis, treatment
    LABORATORY = "laboratory"  # Lab workflows, QC, analysis
    PHARMACEUTICAL = "pharmaceutical"  # Drug management, interactions
    EMERGENCY = "emergency"  # Emergency protocols, triage
    RADIOLOGY = "radiology"  # Imaging workflows
    ANESTHESIA = "anesthesia"  # Anesthesia protocols
    NURSING = "nursing"  # Nursing workflows
    ADMINISTRATIVE = "administrative"  # Hospital operations
    EDUCATIONAL = "educational"  # Training, competency
    LOGISTICS = "logistics"  # Supply chain, inventory
    FINANCIAL = "financial"  # Billing, insurance
    RESEARCH = "research"  # Clinical research
    FIELD_OPS = "field_ops"  # Community health, field clinics
    CUSTOM = "custom"  # User-defined


class IntelligenceLevel(str, Enum):
    """
    Depth of domain expertise encoded in the intelligence.
    """

    STARTER = "starter"  # Basic workflows, simple checklists
    PRACTITIONER = "practitioner"  # Standard clinical workflows
    EXPERT = "expert"  # Advanced protocols, analytics, decision support
    SPECIALIST = "specialist"  # Sub-specialty depth, research-grade


class CreatorVerification(str, Enum):
    """Creator verification levels"""

    UNVERIFIED = "unverified"
    EMAIL_VERIFIED = "email_verified"
    CREDENTIAL_VERIFIED = "credential_verified"  # Medical license confirmed
    PLATFORM_VERIFIED = "platform_verified"  # YAZ team verified


class LicenseModel(str, Enum):
    """Dual licensing models for intelligences"""

    OPEN_ONLY = "open_only"  # Free for everyone, no commercial tier
    DUAL = "dual"  # Open for public, licensed for profit
    COMMERCIAL_ONLY = "commercial_only"  # Paid only
    CUSTOM = "custom"  # Custom licensing arrangement


# ============================================================================
# CREATOR PROFILE
# ============================================================================


class CreatorProfile(SQLModel, table=True):
    """
    Creator profile — practitioners who build intelligences.

    A Creator is a domain expert (surgeon, pharmacist, lab scientist, etc.)
    who encodes their expertise into tools on the YAZ platform.

    First Creator: Dr. Anass Elamrani (Surgio — Surgical Intelligence)

    Creators can:
    - Build intelligences from their practice
    - Publish them free for learners and public institutions
    - License them for private/for-profit entities
    - Fork existing intelligences to create variants
    - Earn revenue from commercial licenses

    Security: No PHI stored. Public profile data only.
    """

    __tablename__ = "creator_profiles"
    __table_args__ = {"schema": "platform", "extend_existing": True}

    # Identity
    id: UUID = Field(default_factory=uuid4, primary_key=True)
    user_id: UUID = Field(unique=True, index=True, description="Platform user ID")
    tenant_id: UUID = Field(index=True, description="Creator's home tenant")

    # Public Identity
    slug: str = Field(max_length=100, unique=True, index=True)
    display_name: str = Field(max_length=200)
    title: str | None = Field(default=None, max_length=300)
    bio: str | None = Field(default=None, max_length=3000)
    philosophy: str | None = Field(default=None, max_length=2000)

    # Professional Info
    specialties: list[str] = Field(default_factory=list, sa_column=Column(JSON))
    credentials: str | None = Field(default=None, max_length=500)
    institution: str | None = Field(default=None, max_length=300)
    country: str | None = Field(default=None, max_length=100)
    language: str = Field(default="en", max_length=10)

    # Contact & Links
    contact_email: str | None = Field(default=None, max_length=300)
    website: str | None = Field(default=None, max_length=500)
    profile_image_url: str | None = Field(default=None, max_length=500)

    # Verification
    verification_level: CreatorVerification = Field(default=CreatorVerification.UNVERIFIED)
    verified_at: datetime | None = Field(default=None)
    verified_by: UUID | None = Field(default=None)

    # Portfolio Stats (aggregated)
    intelligence_count: int = Field(default=0)
    total_installs: int = Field(default=0)
    total_forks: int = Field(default=0)
    total_cases_powered: int = Field(default=0)
    average_rating: Decimal = Field(default=Decimal("0.0"))

    # Revenue (from licensed intelligences)
    total_earnings: Decimal = Field(default=Decimal("0.0"))
    pending_payout: Decimal = Field(default=Decimal("0.0"))
    payout_method: str | None = Field(default=None, max_length=50)

    # Timestamps
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))

    def to_dict_public(self) -> dict[str, Any]:
        """Public-facing creator profile (no revenue details)."""
        return {
            "id": str(self.id),
            "slug": self.slug,
            "display_name": self.display_name,
            "title": self.title,
            "bio": self.bio,
            "philosophy": self.philosophy,
            "specialties": self.specialties,
            "credentials": self.credentials,
            "institution": self.institution,
            "country": self.country,
            "language": self.language,
            "website": self.website,
            "profile_image_url": self.profile_image_url,
            "verification_level": self.verification_level.value,
            "intelligence_count": self.intelligence_count,
            "total_installs": self.total_installs,
            "total_forks": self.total_forks,
            "average_rating": float(self.average_rating),
        }

    def to_dict_owner(self) -> dict[str, Any]:
        """Full profile for the creator themselves (includes revenue)."""
        data = self.to_dict_public()
        data.update(
            {
                "total_cases_powered": self.total_cases_powered,
                "total_earnings": float(self.total_earnings),
                "pending_payout": float(self.pending_payout),
                "payout_method": self.payout_method,
            }
        )
        return data


# ============================================================================
# INTELLIGENCE METADATA (extends Tool)
# ============================================================================


class IntelligenceMetadata(SQLModel, table=True):
    """
    Intelligence metadata — extends a Tool with intelligence classification.

    This is a 1:1 extension of the Tool entity in core.tools.models.
    When a Tool is classified as an "intelligence", this metadata defines
    its expertise level, knowledge base, and licensing model.

    Architecture:
        Tool (core.tools.models) ← base entity
        IntelligenceMetadata     ← intelligence-specific extension

    An Intelligence is more than a tool:
    - It encodes domain expertise (not just UI/workflows)
    - It has a creator with verified credentials
    - It follows dual licensing (open + commercial)
    - It can be forked, extended, and specialized
    """

    __tablename__ = "intelligence_metadata"
    __table_args__ = {"schema": "platform", "extend_existing": True}

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    slug: str = Field(max_length=100, index=True, default="", description="URL-friendly identifier")
    name: str = Field(max_length=200, default="", description="Human-readable name")
    tool_id: UUID = Field(unique=True, index=True, description="FK to platform.tools")
    creator_id: UUID = Field(index=True, description="FK to creator_profiles")

    # Intelligence Classification
    intelligence_class: IntelligenceClass = Field(index=True)
    intelligence_level: IntelligenceLevel = Field(default=IntelligenceLevel.PRACTITIONER)

    # Knowledge Base
    knowledge_domains: list[str] = Field(
        default_factory=list,
        sa_column=Column(JSON),
        description="Specific knowledge areas (e.g., 'visceral_surgery', 'laparoscopy')",
    )
    clinical_standards: list[str] = Field(
        default_factory=list,
        sa_column=Column(JSON),
        description="Standards implemented (e.g., 'WHO SSC 2.0', 'ASA Classification')",
    )
    protocols_count: int = Field(default=0)
    checklists_count: int = Field(default=0)
    algorithms_count: int = Field(default=0)

    # Licensing Model
    license_model: LicenseModel = Field(default=LicenseModel.DUAL)
    open_license: str = Field(default="AGPL-3.0", max_length=50)
    commercial_license: str | None = Field(default="Commercial License", max_length=100)

    # Open License Details
    open_eligible: list[str] = Field(
        default_factory=lambda: [
            "Residents and trainees",
            "Medical students",
            "Public hospitals",
            "University hospitals",
            "Non-profit organizations",
            "NGOs and humanitarian missions",
            "Academic research institutions",
        ],
        sa_column=Column(JSON),
    )

    # Fork & Derivative Info
    is_fork: bool = Field(default=False)
    forked_from_id: UUID | None = Field(default=None)
    fork_count: int = Field(default=0)
    allows_forking: bool = Field(default=True)

    # Quality & Validation
    peer_reviewed: bool = Field(default=False)
    clinically_validated: bool = Field(default=False)
    validation_notes: str | None = Field(default=None, max_length=2000)

    # Timestamps
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))

    def to_dict(self) -> dict[str, Any]:
        return {
            "id": str(self.id),
            "slug": self.slug,
            "name": self.name,
            "tool_id": str(self.tool_id),
            "creator_id": str(self.creator_id),
            "intelligence_class": self.intelligence_class.value,
            "intelligence_level": self.intelligence_level.value,
            "knowledge_domains": self.knowledge_domains,
            "clinical_standards": self.clinical_standards,
            "license_model": self.license_model.value,
            "open_license": self.open_license,
            "is_fork": self.is_fork,
            "fork_count": self.fork_count,
            "peer_reviewed": self.peer_reviewed,
            "clinically_validated": self.clinically_validated,
        }


# ============================================================================
# PYDANTIC SCHEMAS
# ============================================================================


class CreatorProfileCreate(BaseModel):
    """Create a new creator profile."""

    slug: str = PydanticField(..., min_length=3, max_length=100)
    display_name: str = PydanticField(..., min_length=2, max_length=200)
    title: str | None = PydanticField(None, max_length=300)
    bio: str | None = PydanticField(None, max_length=3000)
    philosophy: str | None = PydanticField(None, max_length=2000)
    specialties: list[str] = PydanticField(default_factory=list)
    credentials: str | None = PydanticField(None, max_length=500)
    institution: str | None = PydanticField(None, max_length=300)
    country: str | None = PydanticField(None, max_length=100)
    language: str = PydanticField("en", max_length=10)
    contact_email: str | None = PydanticField(None, max_length=300)
    website: str | None = PydanticField(None, max_length=500)

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [
                {
                    "slug": "dr-anass-elamrani",
                    "display_name": "Dr. Anass Elamrani",
                    "title": "Chirurgien Viscéral & Digestif",
                    "specialties": ["Visceral Surgery", "Digestive Surgery", "Laparoscopy"],
                    "country": "Morocco",
                    "language": "fr",
                }
            ]
        }
    )


class CreatorProfileResponse(BaseModel):
    """Public creator profile response."""

    id: UUID
    slug: str
    display_name: str
    title: str | None
    bio: str | None
    philosophy: str | None
    specialties: list[str]
    credentials: str | None
    institution: str | None
    country: str | None
    language: str
    website: str | None
    profile_image_url: str | None
    verification_level: CreatorVerification
    intelligence_count: int
    total_installs: int
    total_forks: int
    average_rating: float
    created_at: datetime

    model_config = ConfigDict(from_attributes=True)


class IntelligenceCreate(BaseModel):
    """Register a tool as an intelligence."""

    tool_id: UUID
    intelligence_class: IntelligenceClass
    intelligence_level: IntelligenceLevel = IntelligenceLevel.PRACTITIONER
    knowledge_domains: list[str] = PydanticField(default_factory=list)
    clinical_standards: list[str] = PydanticField(default_factory=list)
    license_model: LicenseModel = LicenseModel.DUAL
    open_license: str = PydanticField("AGPL-3.0", max_length=50)
    allows_forking: bool = True

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [
                {
                    "tool_id": "00000000-0000-0000-0000-000000000001",
                    "intelligence_class": "surgical",
                    "intelligence_level": "expert",
                    "knowledge_domains": ["visceral_surgery", "digestive_surgery", "laparoscopy"],
                    "clinical_standards": ["WHO SSC 2.0", "ASA Classification", "ERAS"],
                    "license_model": "dual",
                }
            ]
        }
    )


class IntelligenceResponse(BaseModel):
    """Intelligence metadata response."""

    id: UUID
    tool_id: UUID
    creator_id: UUID
    intelligence_class: IntelligenceClass
    intelligence_level: IntelligenceLevel
    knowledge_domains: list[str]
    clinical_standards: list[str]
    license_model: LicenseModel
    open_license: str
    is_fork: bool
    fork_count: int
    allows_forking: bool
    peer_reviewed: bool
    clinically_validated: bool
    created_at: datetime

    model_config = ConfigDict(from_attributes=True)


# ============================================================================
# EXPORTS
# ============================================================================

__all__ = [
    # Enums
    "IntelligenceClass",
    "IntelligenceLevel",
    "CreatorVerification",
    "LicenseModel",
    # Models
    "CreatorProfile",
    "IntelligenceMetadata",
    # Schemas
    "CreatorProfileCreate",
    "CreatorProfileResponse",
    "IntelligenceCreate",
    "IntelligenceResponse",
]