# -*- coding: utf-8 -*-
from caches.settings_cache import get_setting
from modules.utils import extract_json_object
# from modules.kodi_utils import logger

def models():
	return (
	'llama-3.3-70b-versatile',
	'qwen/qwen3-32b')

def model_payload(model_id, content):
	return {
		'llama-3.3-70b-versatile': {
			'model': 'llama-3.3-70b-versatile',
			'messages': [{'role': 'user', 'content': content}],
			'temperature': 0.7, 
			'response_format': {'type': 'json_object'}},
		'meta-llama/llama-4-scout-17b-16e-instruct': {
			'model': 'meta-llama/llama-4-scout-17b-16e-instruct',
			'messages': [{'role': 'user', 'content': content}],
			'temperature': 0.6, 
			'response_format': {'type': 'json_object'}},
		'qwen/qwen3-32b': {
			'model': 'qwen/qwen3-32b',
			'messages': [{'role': 'user', 'content': content}],
			'temperature': 0.5, 
			'response_format': {'type': 'json_object'}},
		}[model_id]

def similar_prompt():
	return '''
Recommend EXACTLY LIMIT_HERE MEDIA_TYPE_HERE based on

MEDIA_TYPE: MEDIA_TYPE_HERE
TITLE: TITLE_HERE
YEAR: YEAR_HERE
PLOT: PLOT_HERE
GENRES: GENRES_HERE
KEYWORDS: KEYWORDS_HERE

If MEDIA_TYPE is "Movie" recommend ONLY movies otherwise recommend ONLY TV series / mini-series.
Respond ONLY with one JSON array in this exact shape. No other text.

{
  "recommendations": [
	{
	  "title": "Title 1",
	  "year": 2000,
	  "type": "Movie"  // or "Show"
	}
  ]
}

If a title would contain double quotes, replace them with single quotes (').
Don't include year in title.
'''.strip()

def recommendation_prompt():
	return """
You are a brilliant cinema expert and a deeply intuitive, psychological movie and television recommendation engine. Your task is to interpret a user's exact taste profile 
and provide highly targeted, accurate content recommendations.

The user has selected the following specific content profile:
Category Track: CATEGORY_NAME_HERE
Sub-Category: SUB_CATEGORY_NAME_HERE
Description: DESCRIPTION_HERE

STRICT MEDIA TYPE CONSTRAINT:
- You must ONLY recommend content where the format is: MEDIA_TYPE_HERE
- Do NOT mix formats. If 'Movie' is requested, do not include TV series or mini-series. If 'TV Show' is requested, do not include feature films.
- Follow the Time Period or Era guidelines explicitly if provided in the Description above; otherwise, attempt to recommend content produced after the Year 2000.

CRITICAL RECOGNITION ELEMENTS:
- Thematic Anchors: ANCHORS_HERE
- Tonal Profile: TONES_HERE
- Cinematic Benchmarks (FORBIDDEN TO RECOMMEND): BENCHMARKS_HERE

### CORE PSYCHOLOGICAL BALANCING LAWS:
1. BENCHMARK BAN: Look at the 'Cinematic Benchmarks' list provided. You are STRICTLY FORBIDDEN from recommending those exact titles. Instead, treat those titles as perfect stylistic, 
aesthetic, and narrative goals. Find other titles that feel mathematically similar in tone and structure.
2. ACCURACY TRAP: Ensure that the spelling of titles and their release years are 100% factual. Do not make up titles or guess release years.
3. FRESH BALANCE: Provide a diverse mix of widely known cinematic masterpieces and high-quality, hidden gems. Ensure the list has high-utility value.

Please provide a JSON object containing exactly LIMIT_HERE highly targeted MEDIA_TYPE_HERE recommendations based on this profile.

### CRITICAL OUTPUT RULE:
You must return ONLY a raw JSON array of objects. Do not include markdown code blocks (e.g. do NOT wrap the text in ```json ... ```), and do not include any introductory or 
concluding conversational text. Your output must be instantly parseable by `json.loads()` in Python.

### Respond ONLY with one JSON array in this exact shape. No other text.

{
  "recommendations": [
	{
	  "title": "Title 1",
	  "year": 2000,
	  "type": "Movie"  // or "Show"
	}
  ]
}
""".strip()

def response_parse(data):
	content = data.get('choices', [{}])[0].get('message', {}).get('content', '') or ''
	if not content: return {}
	return extract_json_object(content)

def model_info_similar(model_id, media_type, meta, limit):
	payload = model_payload(model_id, make_similar_prompt(media_type, meta, limit))
	return {'similar': {'headers': {'Authorization': 'Bearer %s' % get_api(), 'Content-Type': 'application/json'}, 'url': 'https://api.groq.com/openai/v1/chat/completions',
			'payload': payload, 'parse': response_parse}}

def make_similar_prompt(media_type, meta, limit):
	meta_get = meta.get
	title, year = meta_get('title').strip(), meta_get('year', '')
	plot, genre = meta_get('plot', '').strip(), ','.join([i for i in meta_get('genre') if i]) if meta_get('genre') else 'unknown'
	keywords = ','.join([i['name'] for i in meta_get('keywords', {}).get('keywords')]) if meta_get('keywords', {}).get('keywords') else ''
	prompt = similar_prompt()
	prompt = prompt.replace('MEDIA_TYPE_HERE', media_type).replace('TITLE_HERE', title).replace('YEAR_HERE', year)
	prompt = prompt.replace('PLOT_HERE', plot).replace('GENRES_HERE', genre).replace('KEYWORDS_HERE', keywords)
	prompt = prompt.replace('LIMIT_HERE', str(limit))
	return prompt

def model_info_recommendation(model_id, media_type, recommendation_info, limit):
	payload = model_payload(model_id, make_recommendation_prompt(media_type, recommendation_info, limit))
	return {'recommendation': {'headers': {'Authorization': 'Bearer %s' % get_api(), 'Content-Type': 'application/json'}, 'url': 'https://api.groq.com/openai/v1/chat/completions',
			'payload': payload, 'parse': response_parse}}

def make_recommendation_prompt(media_type, recommendation_info, limit):
	sub_category = recommendation_info['sub_category']
	description = recommendation_info['description']
	anchors = ', '.join(recommendation_info['thematic_anchors'])
	tones = ', '.join(recommendation_info['tonal_profile'])
	benchmarks = ', '.join(recommendation_info['cinematic_benchmarks'])
	prompt = recommendation_prompt()
	prompt = prompt.replace('MEDIA_TYPE_HERE', media_type).replace('SUB_CATEGORY_NAME_HERE', sub_category).replace('DESCRIPTION_HERE', description)
	prompt = prompt.replace('ANCHORS_HERE', anchors).replace('TONES_HERE', tones).replace('BENCHMARKS_HERE', benchmarks)
	prompt = prompt.replace('LIMIT_HERE', str(limit))
	return prompt

def model_present(model_id):
	return model_id in models()

def get_api():
	return get_setting('fen.groq_api')
