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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
# import json
# from groq import Groq
# import os
# from dotenv import load_dotenv
# import random
# from utils import get_random, get_mongo_collection

# load_dotenv()
# some = get_random()
# GROQ_API_KEY = os.getenv(f"GROQ_API_KEY{some}")



# def count_doshas(user_id):
#     collection = get_mongo_collection()
#     cursor = collection.find({"templateName":"Kapha,Pitta,Vata"},{"userId":user_id}).sort("createdAt", -1).limit(1)
#     mapping = {'1':'Vata','2':'Pitta','3':'Kapha'}
#     counts = {"Vata": 0, "Pitta": 0, "Kapha": 0}
#     for item in cursor:
#         # print(item)
#         for lst in item["answers"]:
#             # print(mapping[lst['answer'][:1]])
#             counts[mapping[lst['answer'][:1]]] += 1

#     return counts

# def assign_personality(counts):
#     v = counts["Vata"]
#     p = counts["Pitta"]
#     k = counts["Kapha"]

#     # Single dominant dosha
#     if v >= 7: return "Vata"
#     if p >= 7: return "Pitta"
#     if k >= 7: return "Kapha"

#     # Dual dosha
#     if v >= 5 and p >= 5: return "Vata-Pitta"
#     if p >= 5 and k >= 5: return "Pitta-Kapha"
#     if v >= 5 and k >= 5: return "Vata-Kapha"

#     # Tridoshic
#     if v >= 3 and p >= 3 and k >= 3: return "Vata-Pitta-Kapha"

#     return "Unclear"

# # -------------------------------------
# # TRAITS DICTIONARY
# # -------------------------------------

# TRAITS = {
#     "Vata": """
# Vata
# Vata types are quick and agile in their minds with often changing
# interests and inclinations. They are talkative, informed and
# intellectual and can understand many different points of view their minds easily
# waver and can wander out of control. While they may have some knowledge of many
# different subjects, the tend to lack in depth knowledge about one subject specifically.

# They ack determinism and self confidence and often have a negative perception of themselves.
# Vata types suffer most from fear, which is their first reaction to anything new or strange. They like to worry easily get afflicted by anxiety, and usually lack stability. They get saced out and may be absent-minded. Their memory and short-term and erratic. They suffer quickly from overwork and over-exercise and tend to overextend themselves in whatever they do.
# They are good at creative pursuits. They can be highly sociable and like to mix with people of all types. But, when there is too much vata, they tend to become loners and hypersensitive to contact. This is generally because they have too much to say and do not know how to relate it.

# They are the most adaptable to change.

# If there is too much vata, there is a lot of instability and agitation in the mind which results in exccesive worrying and makes problems appear larger than they are. They are prone to premature action and inappropriate action.

# High vata manifests as fear, alienation, and possible nervous breakdowns. They can also suffer from insomnia, tremors, palpitations and rapid shifts of mood.
# """,

#     "Pitta": """
# Pitta
# Pitta types are intelligent, perceptive and discriminating. They have sharp minds and are able to see the world in a clear and systematic manner. However, they can also be opinionated, judgmental and self -righteous.

# They are prone to anger and tend to be aggressive and domineering. They are not afraid of conflict and can be more aggressive when the situation presents itself. They have probing minds and can be good at research. They also have good debating skills.

# They have a hard time seeing someone else’s point of view and may lack compassion. They prefer hierarchy and authority over consensus. They are highly determined people.

# They usually have food self-control but they can be self-absorbed and anti-social.

# High pitta causes aggressiveness and violence.
# """,

#     "Kapha": """
# Kapha
# Kaphas are naturally emotional in temperament and have tremendous love, devotion and loyalty. Negatively, they can have great desire, and may be possessive and greedy. They are romantic, sentimental, and cry easily.

# They are slower in learning than others but they retain what they learn well. They are better at finishing things than they are at starting something new. They are natural followers and like to work in association or within large teams.

# They are stable but can sometimes stagnate. They don’t like change and find it very difficult to change even when they want to. They are friendly to people they know but have difficulty in relating to foreigners.

# Kapha types are least likely to express anti-social behavior but they are preoccupied with what others think about them.

# High kaha cuses metal dullness and poor perception and they tend to suffer from a lack of motivation.

# They tend to want to own and control everything and have a high degree of possessiveness

# They are prone to over-sleeping overindulging.
# """,

#     "Vata-Pitta": """
# Vata – Pitta (VP)
# VP types have the volatility of air and fire combined. Fear and anger mix within them in unpredictable way. If something doesn’t make them fearful, it makes them angry.

# They often look for someone who they can unload their negative emotions on.

# They find it difficult to withstand criticism.

# They are generally highly intelligent and require a lifestyle that can accommodate their volatility.

# They will thrive in an environment that supports them and creates a safe space for them to express their volatility.
# """,

#     "Pitta-Kapha": """
# Pitta – Kapha (PK)
# Pitta kapha types are psychologically strong in general and don’t seek help easily.

# They lack flexibility and adaptability.

# They prefer to be dominating and controlling.

# They tend to be conservative and possessive. This leads them to eventual frustration because they cannot control everything around them.

# They require new activities, new challenges, and new ways to show their creativity.
# """,

#     "Vata-Kapha": """
# Vata – Kapha (VK)
# VK types lack energy, motivation and passion. They sometimes simply do not have the fire to get things started.

# They are often hypersensitive, and passive-dependent.

# They lack the energy to put plans into action.

# They will go out of their way to agree with what you have said.

# They have chameleon-style personalities where they can appear to be what people want them to be. They will often also blame themselves for others’ mistakes.

# They can be highly adaptable and humble.

# They tend to be naïve and need to be more realistic about other people and their motivations.
# """,

#     "Vata-Pitta-Kapha": """
# Vata – Pitta – Kapha (VPK)
# This is very rare that each of the doshas exist in equal amounts.

# Their condition psychologically can be constantly changing and unpredictable.

# Their psychological state is often a reflection of their circumstances rather than their personality.
# """
# }

# def get_traits_for_type(personality_type):
#     return TRAITS.get(personality_type, "No traits found for this type.")

# # -------------------------------------
# # GROQ: GENERATE PSYCHOLOGY REPORT
# # -------------------------------------

# client = Groq(api_key=GROQ_API_KEY)
# def generate_psychology_report(personality_type, traits_text, dosha_counts):
#     prompt = f"""
# You are an expert Ayurvedic psychologist.

# Write a **deeply personal psychological report directly addressing the person as "you"**.
# This should NOT sound like an academic explanation — it should feel like an
# insightful evaluation about them.

# ### REQUIRED STYLE:
# - Address the reader as **"you"** throughout  
# - Tone: warm, empathetic, reflective, personal  
# - Use gentle interpretations (“you often…”, “you tend to…”, “you sometimes struggle…”)  
# - Explore emotional patterns, thought styles, reactions, strengths, blindspots  

# **Formatting Instructions:**
# - The output MUST be in **Markdown**.
# - Use `#` for the Main Title (e.g., # Personality Report Report).
# - Use `##` for Section Headers (e.g., ## Core Personality).
# - Use bullet points `- ` for lists.
# - Use **bold** text for key strengths or warnings.
# - Do not wrap the output in a code block (like ```markdown). Just return the raw markdown.


# ### Input Data
# Personality Type: **{personality_type}**
# Dosha Counts: {dosha_counts}

# Relevant Ayurvedic Traits:
# --------------------------
# {traits_text}

# Begin the personal Markdown report now.
# """

#     completion = client.chat.completions.create(
#         model="openai/gpt-oss-20b",
#         temperature=1.35,
#         max_tokens=3500,
#         messages=[
#             {"role": "system", "content": "You write personal Ayurvedic psychological reports"},
#             {"role": "user", "content": prompt}
#         ]
#     )

#     return completion.choices[0].message.content

# # -------------------------------------
# # SAVE MARKDOWN
# # -------------------------------------

# def save_report(markdown_text, filename="psychology_report.md"):
#     with open(filename, "w", encoding="utf-8") as f:
#         f.write(markdown_text)
#     print(f"Markdown report saved as: {filename}")

# # -------------------------------------
# # MAIN
# # -------------------------------------

# if __name__ == "__main__":
#     answers = load_answers("vpk_user_answers.json")
#     dosha_counts = count_doshas(answers)
#     # print(dosha_counts)
#     personality_type = assign_personality(dosha_counts)
#     # print(personality_type)
#     traits_text = get_traits_for_type(personality_type)
#     # print(traits_text)

#     report_md = generate_psychology_report(personality_type, traits_text, dosha_counts)

#     # save_report(report_md)
#     # print("\nGenerated Report:\n")
#     #print(report_md)





import json
import os
import random
from typing import Dict, Any
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from groq import Groq
from dotenv import load_dotenv
import requests
from bson import ObjectId

from utils import get_random, get_mongo_collection

load_dotenv()

app = FastAPI(title="KPV asessment API")


some = get_random()
GROQ_API_KEY = os.getenv(f"GROQ_API_KEY{some}")
client = Groq(api_key=GROQ_API_KEY)

class ReportRequest(BaseModel):
    user_id: str
    username: str

class ReportResponse(BaseModel):
    user_id: str
    personality_type: str
    dosha_counts: Dict[str, int]
    report_markdown: str



def count_doshas(userid):
    collection = get_mongo_collection()
    cursor = collection.find({"templateName": "Kapha,Pitta,Vata","userId": userid}).sort("createdAt", -1).limit(1)
    
    mapping = {'1': 'Vata', '2': 'Pitta', '3': 'Kapha'}
    counts = {"Vata": 0, "Pitta": 0, "Kapha": 0}
    
    found_data = False
    for item in cursor:
        found_data = True
        if "answers" in item:
            for lst in item["answers"]:
                if 'answer' in lst and lst['answer']:
                    key = lst['answer'][:1]
                    if key in mapping:
                        counts[mapping[key]] += 1
    
    if not found_data:
        return None 
        
    return counts

def assign_personality(counts):
    v = counts["Vata"]
    p = counts["Pitta"]
    k = counts["Kapha"]


    if v >= 7: return "Vata"
    if p >= 7: return "Pitta"
    if k >= 7: return "Kapha"


    if v >= 5 and p >= 5: return "Vata-Pitta"
    if p >= 5 and k >= 5: return "Pitta-Kapha"
    if v >= 5 and k >= 5: return "Vata-Kapha"

    if v >= 3 and p >= 3 and k >= 3: return "Vata-Pitta-Kapha"

    return "Unclear"



TRAITS = {
    "Vata": """
Vata
Vata types are quick and agile in their minds with often changing
interests and inclinations. They are talkative, informed and
intellectual and can understand many different points of view their minds easily
waver and can wander out of control. While they may have some knowledge of many
different subjects, the tend to lack in depth knowledge about one subject specifically.

They ack determinism and self confidence and often have a negative perception of themselves.
Vata types suffer most from fear, which is their first reaction to anything new or strange. They like to worry easily get afflicted by anxiety, and usually lack stability. They get saced out and may be absent-minded. Their memory and short-term and erratic. They suffer quickly from overwork and over-exercise and tend to overextend themselves in whatever they do.
They are good at creative pursuits. They can be highly sociable and like to mix with people of all types. But, when there is too much vata, they tend to become loners and hypersensitive to contact. This is generally because they have too much to say and do not know how to relate it.

They are the most adaptable to change.

If there is too much vata, there is a lot of instability and agitation in the mind which results in exccesive worrying and makes problems appear larger than they are. They are prone to premature action and inappropriate action.

High vata manifests as fear, alienation, and possible nervous breakdowns. They can also suffer from insomnia, tremors, palpitations and rapid shifts of mood.
""",

    "Pitta": """
Pitta
Pitta types are intelligent, perceptive and discriminating. They have sharp minds and are able to see the world in a clear and systematic manner. However, they can also be opinionated, judgmental and self -righteous.

They are prone to anger and tend to be aggressive and domineering. They are not afraid of conflict and can be more aggressive when the situation presents itself. They have probing minds and can be good at research. They also have good debating skills.

They have a hard time seeing someone else’s point of view and may lack compassion. They prefer hierarchy and authority over consensus. They are highly determined people.

They usually have food self-control but they can be self-absorbed and anti-social.

High pitta causes aggressiveness and violence.
""",

    "Kapha": """
Kapha
Kaphas are naturally emotional in temperament and have tremendous love, devotion and loyalty. Negatively, they can have great desire, and may be possessive and greedy. They are romantic, sentimental, and cry easily.

They are slower in learning than others but they retain what they learn well. They are better at finishing things than they are at starting something new. They are natural followers and like to work in association or within large teams.

They are stable but can sometimes stagnate. They don’t like change and find it very difficult to change even when they want to. They are friendly to people they know but have difficulty in relating to foreigners.

Kapha types are least likely to express anti-social behavior but they are preoccupied with what others think about them.

High kaha cuses metal dullness and poor perception and they tend to suffer from a lack of motivation.

They tend to want to own and control everything and have a high degree of possessiveness

They are prone to over-sleeping overindulging.
""",

    "Vata-Pitta": """
Vata – Pitta (VP)
VP types have the volatility of air and fire combined. Fear and anger mix within them in unpredictable way. If something doesn’t make them fearful, it makes them angry.

They often look for someone who they can unload their negative emotions on.

They find it difficult to withstand criticism.

They are generally highly intelligent and require a lifestyle that can accommodate their volatility.

They will thrive in an environment that supports them and creates a safe space for them to express their volatility.
""",

    "Pitta-Kapha": """
Pitta – Kapha (PK)
Pitta kapha types are psychologically strong in general and don’t seek help easily.

They lack flexibility and adaptability.

They prefer to be dominating and controlling.

They tend to be conservative and possessive. This leads them to eventual frustration because they cannot control everything around them.

They require new activities, new challenges, and new ways to show their creativity.
""",

    "Vata-Kapha": """
Vata – Kapha (VK)
VK types lack energy, motivation and passion. They sometimes simply do not have the fire to get things started.

They are often hypersensitive, and passive-dependent.

They lack the energy to put plans into action.

They will go out of their way to agree with what you have said.

They have chameleon-style personalities where they can appear to be what people want them to be. They will often also blame themselves for others’ mistakes.

They can be highly adaptable and humble.

They tend to be naïve and need to be more realistic about other people and their motivations.
""",

    "Vata-Pitta-Kapha": """
Vata – Pitta – Kapha (VPK)
This is very rare that each of the doshas exist in equal amounts.

Their condition psychologically can be constantly changing and unpredictable.

Their psychological state is often a reflection of their circumstances rather than their personality.
"""
}

def get_traits_for_type(personality_type):
    return TRAITS.get(personality_type, "No traits found for this type.")


def generate_psychology_report(personality_type, traits_text, dosha_counts, request: ReportRequest):
    prompt = f"""
You are an expert Ayurvedic psychologist.

Write a **deeply personal psychological report directly addressing the person as "you"**.
You can start with greetings and name of the person: {request.username}
This should NOT sound like an academic explanation — it should feel like an
insightful evaluation about them.

### REQUIRED STYLE:
- Address the reader as **"you"** throughout  
- Tone: warm, empathetic, reflective, personal  
- Use gentle interpretations (“you often…”, “you tend to…”, “you sometimes struggle…”)  
- Explore emotional patterns, thought styles, reactions, strengths, blindspots  

**Formatting Instructions:**
- The output MUST be in **Markdown**.
- Use `#` for the Main Title (e.g., # Personality Report Report).
- Use `##` for Section Headers (e.g., ## Core Personality).
- Use bullet points `- ` for lists.
- Use **bold** text for key strengths or warnings.
- Do not wrap the output in a code block (like ```markdown). Just return the raw markdown.


### Input Data
Personality Type: **{personality_type}**
Dosha Counts: {dosha_counts}

Relevant Ayurvedic Traits:
--------------------------
{traits_text}

Begin the personal Markdown report now.
"""

    completion = client.chat.completions.create(
        model="openai/gpt-oss-20b", # Ensure this model ID is correct for your Groq access
        temperature=0.5,
        max_tokens=4000,
        messages=[
            {"role": "system", "content": "You write personal Ayurvedic psychological reports"},
            {"role": "user", "content": prompt}
        ]
    )

    return completion.choices[0].message.content


@app.get("/")
def home():
    return {"status": "Ayurvedic Report Service is Running"}

@app.post("/cron_test_KPV")
async def cron_test():
    return "Hello Cron Tester"


@app.post("/generate-report", response_model=ReportResponse)
def create_report(request: ReportRequest):
    try:
        dosha_counts = count_doshas(request.user_id)
        
        if dosha_counts is None:
             raise HTTPException(status_code=404, detail="User data or survey answers not found")

        personality_type = assign_personality(dosha_counts)
        
        traits_text = get_traits_for_type(personality_type)
        report_md = generate_psychology_report(personality_type, traits_text, dosha_counts,request)

        return ReportResponse(
            user_id=request.user_id,
            personality_type=personality_type,
            dosha_counts=dosha_counts,
            report_markdown=report_md
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# To run locally:
# uvicorn main:app --reload