__all__ = ["AI_Tools_LMMH","LMMH_to_Text","Text_to_LMMH"]


from flask import Flask, request, jsonify, Response, send_file, stream_with_context, send_from_directory
from .File_Text_utils import Extract_Text_LMMH,Save_Data_in_History_LMMH,Detect_Language_LMMH
from .intro import Intro_LMMH,Sub_Intro_LMMH
from .DEI_utils import Process_Image_LMMH
import requests
import json

latest_content = None

import re

from googletrans import Translator
    
translator = Translator()

def Run_Model_Stream_LMMH(file_content, HISTORY_FOLDER, Message, Tool, prompt, OA_URL, MODEL_NAME, MODEL_B,Lang_Code):
    # Check if user is asking about the model
    model_info_keywords = [    "what model",
    "which model",
    "model name",
    "what is this model",
    "about the model",
    "who made this model",
    "who created this model",
    "who developed this model",
    "model developer",
    "model creator",
    "who is the developer",
    "who built this model",
    "tell me about the model",
    "model info",
    "model information",
    "developer name",
    "who programmed this",
    "who coded this",
    "who owns this model",
    "who is behind this model",
    "who trained this model",
    "details about the model",
    "model details",
    "origin of the model",
    "model history",
    "model background",
    "model authors",
    "model engineers",
    "developer of the model",
    "creator of the model",
    "who made you",
    "who developed you",
    "who built you",]
    # ✅ Custom streaming response for model info questions
    if any(keyword in prompt.lower() for keyword in model_info_keywords):
        prompt = 'what is your name ?'
        
        
        
        
        


    # Construct model name
    if MODEL_NAME == 'RTA-r1':
        Sub_MODEL_NAME = f'deepseek-r1:{MODEL_B}b'  
    else:
        Sub_MODEL_NAME = f'{MODEL_NAME}:{MODEL_B}b'      



    # Make streaming request to OA_URL
    response = requests.post(
        f"{OA_URL}/api/generate",
        json={"model": Sub_MODEL_NAME, "prompt": prompt, "stream": True},
        stream=True,
    )

    full_response = []

    last = ''
    for line in response.iter_lines():
        if line:
            token = json.loads(line.decode("utf-8")).get("response", "")
            
            token = re.sub(r'[\u4e00-\u9fff\u3040-\u30ff\u0E00-\u0E7F\u0400-\u04FF]+', '', token)

            # Optional: Remove specific Vietnamese words (or use custom detection)
            vietnamese_words = ['dự', 'kiến']
            for vw in vietnamese_words:
                token = token.replace(vw, '')
            
            token = token.replace("DeepSeek", "**ChatRTA**")            
            token = token.replace("deepseek", "**ChatRTA**")            
            token = token.replace("Deepseek", "**ChatRTA**")            
            token = token.replace("deepSeek", "**ChatRTA**")            
            token = token.replace("DEEPSEEK", "**ChatRTA**")           
            token = token.replace("DeepSeek-R", "**ChatRTA R2**")         
            token = token.replace("DeepSeek.", "**ChatRTA**")
            

            text = token.lower()
            if last == ' deep' and text == 'seek':
                token = ' **ChatRTA** Created by ENG.Laith M. M. AL-Haware '
                
                
            last = token.lower()
            if text == ' deep':
                token = ''
                
            full_response.append(token)

            yield token
                
    
    if Lang_Code != "en":
        yield "\n\n"
        # Create a variable to store the combined text excluding <think> content
        combined_text = ""
        inside_think_tag = False
    
        # Iterate through the full_response to process each part
        for vw in full_response:
            if re.search(r'<think>', vw):  # Start of <think> tag
                inside_think_tag = True
                combined_text += vw  # Include <think> content as is
            elif re.search(r'</think>', vw):  # End of <think> tag
                inside_think_tag = False
                combined_text += vw  # Include </think> content as is
            elif not inside_think_tag:
                combined_text += vw  # Add text to combined_text if not inside <think> tags

        try:
            combined_text = re.sub(r'<think>|</think>', '', combined_text)
            # Translate the combined text (after skipping <think> tags)
            token22w = translator.translate(combined_text, src="en", dest=Lang_Code)

            translated_text = token22w.text.replace("<<<NEWLINE>>>", "\n")

            # Fix any missing spaces (e.g., token joins, or multi-part translation)


            # Now yield the translated text with proper spacing
            full_response.append(" ,'" + translated_text + "' ")
            yield ("|LMMH*LMMH|" + translated_text + "|LMMH*LMMH|")  # Yield the translated text

        except Exception as e:
            print(f"Translation error: {e}")
            # If translation fails, yield the original combined text
            full_response.append(combined_text)
            yield combined_text

    if file_content != '':    
        Save_Data_in_History_LMMH(file_content,Message,full_response,Tool,HISTORY_FOLDER);
            
     
def LMMH_to_Text(binary_string):
    # Remove extra spaces and split into 8-bit chunks
    binary_values = binary_string.strip().split()
    # Convert each binary to a character
    characters = [chr(int(b, 2)) for b in binary_values]
    return ''.join(characters)
   
def Text_to_LMMH(text):
    return ' '.join(format(ord(char), '08b') for char in text) 
            
def AI_Tools_LMMH(Tool, Message, userName, userPosition, userDepartment, FromEmail, NameRecipient, OA_URL, MODEL_NAME, MODEL_B,latest_content,HISTORY_FOLDER,file_content,AppsMaker_AppName,USERS_FILES_GENERATED):

    Sub_Intro_LMMH();
    Lang_Code = Detect_Language_LMMH(Message)
    if (Lang_Code != 'en'):
        Message22w = translator.translate(Message, src=Detect_Language_LMMH(Message), dest="en")
        Message = Message22w.text


        
        
        
    
    if Tool == 'RTA Agent':
    
        latest_content = LMMH_to_Text(Extract_Text_LMMH('Model.Data/RTA1.LMMH'))

        
        prompt = f"You are Reading this Document,File:\n'''\n{latest_content}\n'''\nUser Question: {Message}"
    elif Tool == 'File Analysis':
       
        if not latest_content:
            return jsonify({"answer": "No document loaded. Please upload a file first."})
            
        # Check if the value starts with the specific prefix
        prefix = "[==[--\"IMAGE\"--]==]"

        if latest_content and latest_content.startswith(prefix):
            value = latest_content[len(prefix):]  # Remove the prefix from the string

            return Process_Image_LMMH(value, Message,USERS_FILES_GENERATED)
            
            
        prompt = f"You are reading this document:\n\n{latest_content}\n\nUser question: {Message}"
    elif Tool == 'Coding':
        prompt = f"Write efficient, well-commented code for: {Message}"
    elif Tool == 'ProtHack':
        prompt = f"Provide cybersecurity advice for: {Message}"
    elif Tool == 'WriteMail':
        prompt = f"Draft professional email for: {Message}\nRecipient: {NameRecipient}\nSender: {userName}, {userPosition}, {userDepartment}, {FromEmail}"
    elif Tool == 'AppsMaker':
        prompt = f"""You are to create a complete **multi-file** mobile-first web project called {AppsMaker_AppName}.  

not from user :
`{Message}`

## Requirements

### 1) Files (hard rule)
- Create **at least 4 files**:
  - `index.html` (onboarding + navigation entry)
  - `styles.css` (global responsive styles, safe-area support)
  - `components.js` (UI components & micro-interactions)
  - `data/sample-data.json` (sample tasks, notes, users)
- Optional extras:
  - `icons.svg` (inline SVG placeholders)
  - `sw.js` (offline cache)
  - `README.md` (brief run instructions)

### 2) Design & UX
- Mobile-first, full-screen layout (100% viewport width & height)
- Modern, minimal, elegant UI
- Smooth transitions & micro-interactions
- Responsive for mobile, tablet, desktop
- Safe top spacing for status bar:
  - CSS: `padding-top: max(12px, env(safe-area-inset-top));`
- Buttons: gradients, hover/tap effects, soft shadows, full-width on phones
- Stylish modals (blur/transparent background), centered
- Bottom tab navigation: **Tasks**, **Notes**, **Settings**
- Onboarding carousel swipe tutorial
- Confirm modals for deletions
- Mobile gestures: swipe left/right to complete/delete, long-press for context actions
- Accessibility: high contrast mode toggle
- All UI elements fully functional

### 3) Features
- Real-time search with suggestions
- Tags & categories with color coding
- Basic Settings page (notifications, themes, account, backup)
- Optional login (local demo stub)
- Calendar for tasks
- Fully working buttons, forms, modals
- Load **sample data** from `data/sample-data.json`

### 4) Technical
- Clean, optimized, production-ready code
- Only allowed images:
  - `/App Designer/static/IMG/background-1.jpg`
  - `/App Designer/static/IMG/background-2.jpg`
  - `/static/IMG/background-3.jpg`
  - `/App Designer/static/IMG/background-4.jpg`
  - `/App Designer/static/IMG/background-5.jpg`
  - `/App Designer/static/IMG/user-1.jfif`
  - `/App Designer/static/IMG/user-2.jpg`
  - `/App Designer/static/IMG/user-3.jpg`
  - `/App Designer/static/IMG/random-1.png`
  - `/App Designer/static/IMG/random-2.jpg`
  - `/App Designer/static/IMG/random-3.jpg`
- Make all images fully responsive:
  - `max-width: 100%; height: auto; object-fit: cover;`

### 5) File output format (strict)
For each file, output **only** in this format:

------start---<file-name>------
[full content]
------end---<file-name>------

Do **not** combine files or output extra text.  

### 6) Absolute prohibitions
- No text outside the start/end blocks
- No inline CSS/JS except <10 lines
- No external references beyond allowed images

**Goal:** Produce a **fully working, modern, elegant, mobile-first app** with **all functionality working**, using **HTML + CSS + JS only**. 
"""
    else:
        prompt = Message
        
    

    # Normally, this would call your AI endpoint; here we just return the prompt for demo
    return Run_Model_Stream_LMMH(file_content,HISTORY_FOLDER,Message,Tool,prompt,OA_URL,MODEL_NAME,MODEL_B,Lang_Code)

