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
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
import os
import json
import subprocess
import ast

# Import strict prompts
from prompt import *

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate


def add_app_to_installed_apps(settings_path: str, app_name: str):
    with open(settings_path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    in_installed_apps = False
    already_added = False
    new_lines = []

    for line in lines:
        if line.strip().startswith("INSTALLED_APPS"):
            in_installed_apps = True

        if in_installed_apps and f'"{app_name}"' in line:
            already_added = True

        if in_installed_apps and line.strip() == "]":
            if not already_added:
                new_lines.append(f'    "{app_name}",\n')
            in_installed_apps = False

        new_lines.append(line)

    if not already_added:
        with open(settings_path, "w", encoding="utf-8") as f:
            f.writelines(new_lines)


# ============================================================
# HELPER FUNCTIONS
# ============================================================

def run_cmd(command, cwd=None):
    """Runs terminal commands safely."""
    result = subprocess.run(
    command.split(),
    cwd=cwd,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)

    
    if result.returncode != 0:
        print("❌ Command failed:", command)
        print(result.stderr)
        raise Exception(result.stderr)
    return result.stdout


def write_file(path, content):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf8") as f:
        f.write(content)


def is_valid_python(code: str) -> bool:
    try:
        ast.parse(code)
        return True
    except:
        return False

# ===================README FILE GENERATOR ===================

def generate_readme_with_llm(spec_json, project_path, llm):
    chain = ChatPromptTemplate.from_messages([
        ("system", README_PROMPT),
        ("user", "{json_input}")
    ])

    runnable = chain | llm
    result = runnable.invoke({
        "json_input": json.dumps(spec_json, indent=2)
    })

    readme_content = result.content.strip()

    write_file(os.path.join(project_path, "README.md"), readme_content)
    print("πŸ“˜ README.md generated successfully.")


# ============================================================
# CUSTOM FILE VALIDATORS
# ============================================================

def is_valid_serializer(code):
    """Rejects dynamic serializer patterns."""
    forbidden = ["globals(", "type(", "for ", "_create", "json_input"]
    if any(f in code for f in forbidden):
        return False
    if "class " not in code:
        return False
    if "Serializer" not in code:
        return False
    return is_valid_python(code)


def is_valid_views(code):
    """Reject dynamic views or helper functions."""
    forbidden = ["globals(", "type(", "_create", "for ", "json_input"]
    if any(f in code for f in forbidden):
        return False
    if "APIView" not in code:
        return False
    return is_valid_python(code)


def is_valid_urls(code):
    forbidden = ["globals(", "type(", "_create", "json_input"]
    if any(f in code for f in forbidden):
        return False
    
    if "urlpatterns" not in code:
        return False
    if "path(" not in code:
        return False
    if "<int:pk>" not in code:
        return False

    # No leading slash allowed
    if 'path("/' in code or "path('/" in code:
        return False

    return is_valid_python(code)


# ============================================================
# GENERATION LOGIC (AUTO-FIX)
# ============================================================

def generate_code_with_fix(
    prompt,
    json_slice,
    *,
    llm,
    validator=None,
    retries=5,
):

    for attempt in range(retries):
        print(f"🧠 Generating (attempt {attempt+1})...")

        chain = ChatPromptTemplate.from_messages([
            ("system", prompt),
            ("user", "{json_input}")
        ])

        runnable = chain | llm
        result = runnable.invoke({
            "json_input": json.dumps(json_slice, indent=2)
        })

        code = result.content.strip()


        # Use custom validator if provided
        if validator:
            if validator(code):
                print("βœ… File valid.")
                return code
        else:
            # Syntax-only validation
            if is_valid_python(code):
                print("βœ… File valid.")
                return code

        print("❌ Invalid file. Regenerating...")

    raise Exception("❌ Could not generate a valid file after retries.")


def generate_urls_with_fix(prompt, json_slice, *, llm, retries=5):
    return generate_code_with_fix(prompt, json_slice, validator=is_valid_urls,llm=llm, retries=retries)


# ============================================================
# MAIN PROJECT GENERATOR
# ============================================================

import os
import sys

def generate_full_project(spec_json, output_dir, llm, project_name):
    print("generating project")
    
    print("creating path")

    project_path = os.path.join(output_dir, project_name)
    os.makedirs(output_dir, exist_ok=True)

    PYTHON = sys.executable  # βœ… always correct python

    # -----------------------------
    # 1) CREATE DJANGO PROJECT
    # -----------------------------
    try:
        print("πŸš€ Creating Django project...")
        run_cmd(f"{PYTHON} -m django startproject {project_name}", cwd=output_dir)
    except Exception as e:
        raise RuntimeError(f"Failed to create Django project '{project_name}'") from e

    # -----------------------------
    # 2) CREATE APPS
    # -----------------------------
    try:
        for app in spec_json.get("apps", {}):
            print(f"πŸ“¦ Creating app: {app}")
            run_cmd(f"{PYTHON} manage.py startapp {app}", cwd=project_path)

            settings_path = os.path.join(
                project_path,
                project_name,
                "settings.py"
            )

            add_app_to_installed_apps(settings_path, app)

    except Exception as e:
        raise RuntimeError("Failed while creating Django apps") from e

    # -----------------------------
    # 3) GENERATE FILES FOR EACH APP
    # -----------------------------
    for app_name, app_spec in spec_json.get("apps", {}).items():
        try:
            print(f"πŸ“ Generating code for app: {app_name}")
            app_dir = os.path.join(project_path, app_name)

            if not os.path.exists(app_dir):
                raise FileNotFoundError(f"App directory not found: {app_dir}")

            models_slice = {"models": app_spec.get("models", {})}

            serializer_slice = {
                "model_names": sorted(app_spec.get("models", {}).keys())
            }
            admin_slice = {"model_names": list(app_spec.get("models", {}).keys())}

            views_slice = {
                "model_names": list(app_spec.get("models", {}).keys()),
                "apis": app_spec.get("apis", {})
            }

            urls_slice = {
                "model_names": list(app_spec.get("models", {}).keys()),
                "apis": app_spec.get("apis", {}),
                "base_url": spec_json.get("api_config", {}).get("base_url", "/api/")
            }

            models_code = generate_code_with_fix(
                MODELS_PROMPT, models_slice, validator=is_valid_python, llm=llm
            )
            write_file(os.path.join(app_dir, "models.py"), models_code)

            serializers_code = generate_code_with_fix(
                SERIALIZERS_PROMPT, serializer_slice, validator=is_valid_serializer, llm=llm
            )
            write_file(os.path.join(app_dir, "serializers.py"), serializers_code)

            views_code = generate_code_with_fix(
                VIEWS_PROMPT, views_slice, validator=is_valid_views, llm=llm
            )
            write_file(os.path.join(app_dir, "views.py"), views_code)

            urls_code = generate_urls_with_fix(
                URLS_PROMPT, urls_slice, llm=llm
            )
            write_file(os.path.join(app_dir, "urls.py"), urls_code)

            admin_code = generate_code_with_fix(
                ADMIN_PROMPT, admin_slice, validator=is_valid_python, llm=llm
            )
            write_file(os.path.join(app_dir, "admin.py"), admin_code)

        except Exception as e:
            raise RuntimeError(f"Code generation failed for app '{app_name}'") from e

    # -----------------------------
    # 4) GENERATE REQUIREMENTS
    # -----------------------------
    try:
        requirements_slice = {
            "auth": spec_json.get("auth", {}),
            "database": spec_json.get("database", {}),
            "deployment": spec_json.get("deployment", {})
        }

        requirements_code = generate_code_with_fix(
            REQUIREMENTS_PROMPT, requirements_slice, llm=llm
        )
        write_file(os.path.join(project_path, "requirements.txt"), requirements_code)

    except Exception as e:
        raise RuntimeError("Failed to generate requirements.txt") from e

    # -----------------------------
    # 5) PROJECT URLS
    # -----------------------------
    try:
        project_urls_slice = {
            "project_name": project_name,
            "apps": list(spec_json.get("apps", {}).keys()),
            "base_url": spec_json.get("api_config", {}).get("base_url", "/api/")
        }

        project_urls_code = generate_code_with_fix(
            PROJECT_URLS_PROMPT,
            project_urls_slice,
            validator=is_valid_python, llm=llm
        )

        write_file(
            os.path.join(project_path, project_name, "urls.py"),
            project_urls_code
        )

    except Exception as e:
        raise RuntimeError("Failed to generate project urls.py") from e

    # -----------------------------
    # 6) README (OPTIONAL)
    # -----------------------------
    try:
        generate_readme_with_llm(spec_json, project_path, llm=llm)
    except Exception as e:
        print("⚠ README generation failed (non-blocking):", e)

    print("\nπŸŽ‰ DONE! Project created at:", project_path)
    return project_path

def load_json_spec(path="json_output/spec.json"):
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


#=============================Prompt_With_Model_Specification================

def generate_django_model_prompt(project_name: str, description: str, llm):
    """
    Uses LLM to generate a high-quality, structured prompt
    for Django model development with clear specifications.
    """

    prompt = ChatPromptTemplate.from_messages([
    ("system", """
You are a senior Django backend architect with production experience.

Your task is to generate a SINGLE, CLEAN, PLAIN-TEXT PROMPT
that will later be used to generate Django models.py.

STRICT RULES:
- Output ONLY plain text.
- Do NOT use markdown, bullet points, headings, or code blocks.
- Do NOT include explanations or commentary.
- Do NOT generate Django code.
- Generate ONLY the final prompt text.

MODEL DESIGN RULES:
- Follow Django ORM best practices.
- Use deterministic, production-ready model structures.
- Infer missing models or fields if required to complete the system.
- Never invent unnecessary models.
- Every model MUST have a clear real-world purpose.

FIELD RULES:
- Infer sensible fields when the user does not specify all required fields.
- Use correct Django field types.
- Add timestamps (created_at, updated_at) when appropriate.
- Use UUID primary keys where suitable.
- Do NOT use dynamic patterns or metaprogramming.
- Ensure field names are snake_case.
- Ensure model names are PascalCase.

RELATIONSHIP RULES:
- Infer relationships only when logically required.
- Use ForeignKey for one-to-many relationships.
- Use OneToOneField only when explicitly required.
- Avoid ManyToMany unless clearly necessary.

META RULES:
- Include Meta options such as db_table and ordering.
- Include __str__ methods for all models.
- Ensure compatibility with Django REST Framework serializers and views.

OUTPUT QUALITY RULE:
The generated prompt must be precise, minimal, and implementation-ready,
so that another LLM can generate models.py without making assumptions.
"""),
    ("user", """
Project Name: {project_name}

User Requirements:
{description}

Generate a single, concise, implementation-ready PROMPT
that instructs an LLM to generate Django models.py.
""")
])


    chain = prompt | llm
    result = chain.invoke({
        "project_name": project_name,
        "description": description
    })

    return result.content.strip()