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
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
"""Render structured agent outputs into human/ops-readable artifacts."""

from __future__ import annotations

import re
from typing import Any

import yaml

from ..schemas import (
    APIOutput,
    ArchitectureOutput,
    DatabaseOutput,
    DevopsOutput,
    ProjectContext,
    RequirementsOutput,
)


def _ul(items: list[str]) -> str:
    return "\n".join(f"- {item}" for item in items) if items else "- _none_"


def _section(title: str, body: str) -> str:
    return f"\n## {title}\n\n{body}\n"


def render_overview(context: ProjectContext) -> str:
    return (
        f"# Project Overview\n\n"
        f"- **Project ID:** `{context.project_id}`\n"
        f"- **Status:** `{context.status}`\n"
        f"\n"
        f"## Business Idea\n\n{context.business_idea}\n"
        + _section("Problem", context.problem or "_not specified_")
        + _section("Target Users", _ul(context.target_users))
        + _section("User Roles", _ul(context.user_roles))
        + _section("Business Goals", _ul(context.business_goals))
        + _section("Core Features", _ul(context.core_features))
        + _section("Scope", context.scope or "_not specified_")
        + _section("Constraints", _ul(context.constraints))
        + _section("Assumptions", _ul(context.assumptions))
        + _section("Integrations", _ul(context.integrations))
        + _section("Security Requirements", _ul(context.security_requirements))
        + _section("Performance Requirements", _ul(context.performance_requirements))
        + _section("Deployment Requirements", _ul(context.deployment_requirements))
        + _section("Technology Preferences", _ul(context.technology_preferences))
        + _section(
            "Auth & Payments",
            (
                f"- Authentication: {context.auth_requirement or '_none_'}\n"
                f"- Authorization: {context.authorization_requirement or '_none_'}\n"
                f"- Payments: {context.payment_requirement or '_none_'}\n"
                f"- Notifications: {context.notification_requirement or '_none_'}\n"
            ),
        )
    )


def render_requirements(output: RequirementsOutput) -> str:
    return (
        "# Requirements Specification\n\n"
        "## Functional Requirements\n\n"
        f"{_ul(output.functional_requirements)}\n"
        + _section("Non-Functional Requirements", _ul(output.non_functional_requirements))
        + _section("User Stories", _ul(output.user_stories))
        + _section("Acceptance Criteria", _ul(output.acceptance_criteria))
        + _section("Constraints", _ul(output.constraints))
        + _section("Assumptions", _ul(output.assumptions))
    )


def render_architecture(output: ArchitectureOutput) -> str:
    components = "\n".join(
        f"- **{c.name}** ({c.type}, {c.technology}) — {c.description}"
        for c in output.system_components
    )
    stack = "\n".join(f"- {k}: {v}" for k, v in output.technology_stack.items())
    diagram = output.mermaid_diagram or _derive_architecture_mermaid(output)
    return (
        "# System Architecture\n\n"
        f"## System Components\n\n{components}\n"
        + _section("Communication", _ul(output.communication))
        + _section("Authentication", output.authentication or "_not specified_")
        + _section("Security", _ul(output.security))
        + _section("Scalability", _ul(output.scalability))
        + _section("Technology Stack", stack)
        + ((_section("Deployment Architecture", output.deployment_architecture)) if output.deployment_architecture else "")
        + _section("Architecture Diagram", f"```mermaid\n{diagram}\n```\n")
    )


def _derive_architecture_mermaid(output: ArchitectureOutput) -> str:
    """Derive a Mermaid flowchart from system_components (replaces LLM-generated diagram)."""
    if not output.system_components:
        return ""
    lines = ["flowchart TD"]
    # Map component names to safe node IDs
    node_ids: dict[str, str] = {}
    for i, c in enumerate(output.system_components):
        nid = re.sub(r"[^A-Za-z0-9]", "_", c.name) or f"node{i}"
        node_ids[c.name] = nid
        label = f"{c.name}\\n[{c.technology}]"
        shape = {
            "frontend": f'{nid}["{label}"]',
            "backend": f'{nid}["{label}"]',
            "database": f'{nid}[("{label}")]',
            "service": f'{nid}(("{label}"))',
            "external": f'{nid}[["{label}"]]',
            "infrastructure": f'{nid}[/"{label}"/]',
        }.get(c.type, f'{nid}["{label}"]')
        lines.append(f"  {shape}")
    # Connect backend -> database, frontend -> backend, service -> database
    type_map: dict[str, list[str]] = {}
    for c in output.system_components:
        type_map.setdefault(c.type, []).append(c.name)
    for src_type, dst_type, label in [
        ("frontend", "backend", "HTTP"),
        ("backend", "database", "SQL"),
        ("backend", "service", "calls"),
        ("backend", "external", "API"),
        ("service", "database", "SQL"),
    ]:
        for src in type_map.get(src_type, []):
            for dst in type_map.get(dst_type, []):
                lines.append(f"  {node_ids[src]} --> {node_ids[dst]}")
    return "\n".join(lines)


def render_architecture_mmd(output: ArchitectureOutput) -> str:
    return output.mermaid_diagram or _derive_architecture_mermaid(output)


def render_database_markdown(output: DatabaseOutput) -> str:
    sections: list[str] = [
        "# Database Design\n\n",
        f"## Database Technology\n\n{output.database_technology}\n",
        "## Entities\n",
    ]
    for entity in output.entities:
        rows = "\n".join(
            f"| {f.name} | {f.type} | {'PK' if f.primary_key else ''} | "
            f"{f.foreign_key or ''} | {'NOT NULL' if not f.nullable else 'NULL'} | "
            f"{'UNIQUE' if f.unique else ''} | {'IDX' if f.indexed else ''} |"
            for f in entity.fields
        )
        header = "| Field | Type | PK | FK | Nullable | Unique | Indexed |\n|---|---|---|---|---|---|---|"
        sections.append(f"\n### {entity.name}\n\n{entity.description}\n\n{header}\n{rows}\n")
    sections.append(_section("Relationships", _ul(output.relationships)))
    # Indexes/constraints are derived from entity fields when not provided by LLM
    derived_indexes = output.indexes or _derive_indexes(output.entities)
    derived_constraints = output.constraints or _derive_constraints(output.entities)
    if derived_indexes:
        sections.append(_section("Indexes", _ul(derived_indexes)))
    if derived_constraints:
        sections.append(_section("Constraints", _ul(derived_constraints)))
    sections.append(_section("ERD", f"```mermaid\n{render_erd(output)}\n```\n"))
    return "\n".join(sections)


def _derive_indexes(entities: list) -> list[str]:
    """Derive index recommendations from entity fields."""
    indexes: list[str] = []
    for e in entities:
        for f in e.fields:
            if f.indexed and not f.primary_key:
                indexes.append(f"CREATE INDEX idx_{e.name}_{f.name} ON {e.name}({f.name});")
            elif f.foreign_key:
                indexes.append(f"CREATE INDEX idx_{e.name}_{f.name} ON {e.name}({f.name}); -- FK index")
    return indexes


def _derive_constraints(entities: list) -> list[str]:
    """Derive table constraints from entity fields."""
    constraints: list[str] = []
    for e in entities:
        for f in e.fields:
            if f.unique and not f.primary_key:
                constraints.append(f"{e.name}.{f.name}: UNIQUE")
            if f.foreign_key:
                constraints.append(f"{e.name}.{f.name} REFERENCES {f.foreign_key} ON DELETE CASCADE")
    return constraints


def _table_order(entities: list) -> list[str]:
    """Order entities so referenced (parent) tables are created first."""
    names = {e.name for e in entities}
    by_name = {e.name: e for e in entities}

    def refs(e) -> list[str]:
        out = []
        for f in e.fields:
            if f.foreign_key and f.foreign_key.split(".")[0] in names:
                parent = f.foreign_key.split(".")[0]
                if parent not in out:
                    out.append(parent)
        return out

    ordered: list[str] = []
    visited: set[str] = set()

    def visit(name: str) -> None:
        if name in visited:
            return
        visited.add(name)
        for parent in refs(by_name[name]):
            visit(parent)
        ordered.append(name)

    for entity in entities:
        visit(entity.name)
    return ordered


def _sql_from_entities(entities: list) -> str:
    """Derive executable SQL DDL from the entity/field definitions."""
    by_name = {e.name: e for e in entities}
    statements: list[str] = []
    for name in _table_order(entities):
        entity = by_name[name]
        columns: list[str] = []
        for f in entity.fields:
            parts = [f.name, f.type or "TEXT"]
            if f.primary_key:
                parts.append("PRIMARY KEY")
            if f.foreign_key:
                parent, _, parent_field = f.foreign_key.partition(".")
                parts.append(f"REFERENCES {parent}({parent_field or 'id'})")
            if not f.nullable:
                parts.append("NOT NULL")
            if f.unique and not f.primary_key:
                parts.append("UNIQUE")
            columns.append(" ".join(parts))
        if not columns:
            continue
        statements.append(f"CREATE TABLE {name} (\n  " + ",\n  ".join(columns) + "\n);")
        for f in entity.fields:
            if f.indexed and not f.primary_key and not f.unique and f.foreign_key is None:
                statements.append(f"CREATE INDEX idx_{name}_{f.name} ON {name} ({f.name});")
    return "\n\n".join(statements)


def _erd_from_entities(entities: list) -> str:
    """Derive a Mermaid erDiagram from entity fields and foreign keys."""
    if not entities:
        return ""
    lines = ["erDiagram"]
    for e in entities:
        if e.fields:
            lines.append(f"  {e.name} {{")
            for f in e.fields:
                lines.append(f"    {f.type or 'TEXT'} {f.name}")
            lines.append("  }")
    for e in entities:
        for f in e.fields:
            if f.foreign_key and "." in f.foreign_key:
                parent, _ = f.foreign_key.split(".", 1)
                lines.append(f'  {parent} ||--o{{ {e.name} : ""')
    return "\n".join(lines)


def render_database_sql(output: DatabaseOutput) -> str:
    return output.sql_schema or _sql_from_entities(output.entities)


def render_erd(output: DatabaseOutput) -> str:
    return output.erd_mermaid or _erd_from_entities(output.entities)


def _operation_id(method: str, path: str) -> str:
    safe = re.sub(r"[^A-Za-z0-9]+", "_", path).strip("_")
    return f"{method.lower()}_{safe or 'root'}"


def _openapi_from_endpoints(output: APIOutput) -> dict:
    """Derive a complete OpenAPI 3.0 document from the endpoint list."""
    paths: dict[str, Any] = {}
    requires_auth = False
    for ep in output.endpoints:
        path_item = paths.setdefault(ep.path, {})
        parameters: list[dict[str, Any]] = []
        if ep.pagination:
            parameters.append(
                {"name": "page", "in": "query", "schema": {"type": "integer"}}
            )
            parameters.append(
                {"name": "page_size", "in": "query", "schema": {"type": "integer"}}
            )
        for name in ep.filters:
            parameters.append({"name": name, "in": "query", "schema": {"type": "string"}})
        operation: dict[str, Any] = {
            "operationId": _operation_id(ep.method, ep.path),
            "summary": ep.summary,
            "parameters": parameters,
            "responses": {"200": {"description": "OK"}},
        }
        if ep.auth and ep.auth != "none":
            requires_auth = True
            operation["security"] = [{"bearerAuth": []}]
        if ep.request_schema:
            operation["requestBody"] = {
                "required": True,
                "content": {"application/json": {"schema": ep.request_schema}},
            }
        if ep.response_schema:
            operation["responses"]["200"]["content"] = {
                "application/json": {"schema": ep.response_schema}
            }
        path_item[ep.method.lower()] = operation

    spec: dict[str, Any] = {
        "openapi": "3.0.0",
        "info": {"title": "API", "version": "1.0.0"},
        "paths": paths,
    }
    if requires_auth:
        spec["components"] = {
            "securitySchemes": {"bearerAuth": {"type": "http", "scheme": "bearer"}}
        }
    return spec


def render_openapi(output: APIOutput) -> str:
    spec = output.openapi_spec or {}
    if not spec:
        spec = _openapi_from_endpoints(output)
    return yaml.safe_dump(spec, sort_keys=False, allow_unicode=True)


def render_api_markdown(output: APIOutput) -> str:
    endpoints = "\n".join(
        f"- **{e.method}** `{e.path}` — {e.summary} (auth: {e.auth})"
        + (f" [filters: {', '.join(e.filters)}]" if e.filters else "")
        + (" [paginated]" if e.pagination else "")
        for e in output.endpoints
    )
    return (
        "# API Design\n\n"
        f"## Endpoints\n\n{endpoints}\n"
        + _section("Authentication", output.authentication or "_not specified_")
        + _section("Authorization", output.authorization or "_not specified_")
        + _section("Error Handling", _ul(output.error_handling))
        + _section("Pagination", output.pagination or "_not specified_")
        + _section("Filtering", output.filtering or "_not specified_")
    )


def render_devops_markdown(output: DevopsOutput) -> str:
    env = "\n".join(f"- `{k}`: {v}" for k, v in output.environment_variables.items())
    return (
        "# DevOps Configuration\n\n"
        + _section("Deployment Strategy", output.deployment_strategy or "_not specified_")
        + _section("Health Checks", _ul(output.health_checks))
        + _section("Logging", _ul(output.logging))
        + _section("Monitoring", _ul(output.monitoring))
        + _section("Secrets Management", output.secrets_management or "_not specified_")
        + _section("CI/CD Pipeline", output.ci_cd_pipeline or "_not specified_")
        + _section("Environment Variables", env)
    )


def render_artifact_payload(artifact: str, output: Any) -> str:
    """Return the rendered text for a single artifact type."""
    if artifact == "requirements":
        return render_requirements(output)
    if artifact == "architecture":
        return render_architecture(output)
    if artifact == "database":
        return render_database_markdown(output)
    if artifact == "api":
        return render_api_markdown(output)
    if artifact == "devops":
        return render_devops_markdown(output)
    raise ValueError(f"Unknown artifact: {artifact}")


def render_all(context: ProjectContext) -> dict[str, str]:
    """Render the complete artifact set for a finished project."""
    files: dict[str, str] = {"overview.md": render_overview(context)}

    if context.requirements:
        output = RequirementsOutput.model_validate(context.requirements)
        files["requirements.md"] = render_requirements(output)

    if context.architecture:
        output = ArchitectureOutput.model_validate(context.architecture)
        files["architecture.md"] = render_architecture(output)
        files["architecture.mmd"] = render_architecture_mmd(output)

    if context.database:
        output = DatabaseOutput.model_validate(context.database)
        files["database.md"] = render_database_markdown(output)
        files["database.sql"] = render_database_sql(output)
        files["erd.mmd"] = render_erd(output)

    if context.api:
        output = APIOutput.model_validate(context.api)
        files["api.md"] = render_api_markdown(output)
        files["openapi.yaml"] = render_openapi(output)

    if context.devops:
        output = DevopsOutput.model_validate(context.devops)
        files["devops.md"] = render_devops_markdown(output)
        files["Dockerfile"] = output.dockerfile
        files["docker-compose.yml"] = output.docker_compose
        files["github-actions.yml"] = output.github_actions

    return files