The input text isnt defined here : """
Gen Z Text Converter using Ollama (Standalone Script)

This script transforms predefined educational text into Gen Z-friendly lingo
using a local language model via Ollama. All inputs are defined within the script.
"""

import requests
import sys
import json

# ------------------------------
# Configuration Section
# ------------------------------

# Define the educational content you want to transform.
# You can modify this string with your desired text.
ORIGINAL_TEXT = """
"""

# Define the name of the Ollama model to use.
# Ensure that the model is installed via Ollama.
MODEL_NAME = "llama3.2:latest"

# Define the output file path where the transformed text will be saved.
OUTPUT_FILE_PATH = "transformed_output.txt"

# Define the Ollama API endpoint.
OLLAMA_API_URL = "http://localhost:11434/v1/chat/completions"

# Define headers for the HTTP request.
HEADERS = {
    "Content-Type": "application/json"
}

# ------------------------------
# Function Definitions
# ------------------------------

def check_model_installed(model_name):
    """
    Checks if the specified Ollama model is installed.

    Args:
        model_name (str): The name of the Ollama model.

    Returns:
        bool: True if installed, False otherwise.
    """
    try:
        response = requests.get("http://localhost:11434/v1/models")
        response.raise_for_status()
        models = response.json().get("data", [])
        
        # Extract model IDs from the data
        installed_models = [model['id'] for model in models]
        
        print("Installed models:", installed_models)  # Debugging output
        
        return model_name in installed_models
    except requests.exceptions.RequestException as e:
        print(f"Error checking installed models: {e}", file=sys.stderr)
        sys.exit(1)
    except (ValueError, json.JSONDecodeError) as e:
        print(f"Error parsing models list: {e}", file=sys.stderr)
        sys.exit(1)
        
def transform_text(input_text, model_name):
    """
    Transforms the input_text using the specified Ollama model.

    Args:
        input_text (str): The original educational text.
        model_name (str): The name of the Ollama language model.

    Returns:
        str: The transformed text in Gen Z lingo.
    """
    prompt = (
        "Most important: It should be addictive and attention grabbing"
        "Convert the text into something that a highchooler can understand"
        "Transform any given text into Gen Z lingo, ensuring the output is long enough to fill 60 to 90 seconds of speaking time. "
        "Make it feel like it’s coming straight from a social media influencer or a friend hyping you up. "
        "Use casual, playful, and energetic language that would resonate with younger audiences. Think of Gen Z’s style on TikTok, Instagram, and Snapchat. "
        "Add phrases and slang like ‘vibes,’ ‘no cap,’ ‘slay,’ ‘Riz,’ ‘bet,’ ‘on point,’ ‘low-key,’ ‘goat,’ and ‘real ones know.’ Incorporate pop culture references "
        "and meme language to create a relatable and humorous tone.\n\n"
        "Here’s what the conversion should look like:\n"
        "- Explain complex topics in a way that’s fun, simple, and memorable. Turn technical words into more familiar terms without losing the meaning.\n"
        "- Make it sound like a pep talk: If the text is instructional or informative, frame it like advice from a friend who’s hyping you up.\n"
        "- Use ‘alpha’ and ‘beta’ metaphors to add a sense of hierarchy or expertise.\n"
        "- Add confidence-boosting elements to make it feel empowering.\n"
        "- Break down boring parts into digestible, high-energy snippets with relatable metaphors.\n"
        "- Use examples and phrases that can instantly spark a visual, like 'think of it like leveling up in a video game' or 'get those knowledge gains.'\n"
        "- Throw in humor, references, and keep the tone light-hearted, so that even if the topic is serious, it feels accessible and fun.\n\n"
        "To help with the style, here’s a list of Gen Z word replacements to swap common phrases with Gen Z-friendly ones:\n"
        "| Normal Word/Phrase     | Gen Z Translation                     |\n"
        "|-----------------------|-------------------------------------|\n"
        "| Important             | Major vibes                         |\n"
        "| Cool                  | Fire / Lit / Sick                   |\n"
        "| Really                | Low-key / High-key                  |\n"
        "| Awesome               | Dope / Sick / Insane                |\n"
        "| Confusing             | Brain-bender                        |\n"
        "| Smart                 | Big brain vibes / Galaxy brain      |\n"
        "| Greatest              | GOAT (Greatest of All Time)        |\n"
        "| Serious               | Deadass / For real                  |\n"
        "| Knowledge             | Knowledge gains / Brain food        |\n"
        "| Old-fashioned         | Boomer vibes                        |\n"
        "| Right answer          | W (Win)                             |\n"
        "| Effort                | Grind / Hustle                      |\n"
        "| No way                | No cap / Bet                        |\n"
        "| Perfect               | On point                            |\n"
        "| Simple                | Low-key easy                        |\n"
        "| Focus                 | Stay woke                           |\n"
        "| Trustworthy           | Real ones know                      |\n"
        "| Amazing               | Mind-blowing / Next-level          |\n"
        "| Try hard              | Sweaty / Overachiever               |\n"
        "| Scared                | Shook / Low-key scared              |\n"
        "| Boring                | Snoozefest                          |\n"
        "| Money                 | Stacks / Bag                        |\n"
        "| Goal                  | Big mood / The vibe                 |\n"
        "| Answer                | Drop the W                          |\n"
        "| Hyped                 | Vibing / Buzzing                    |\n"
        "| Confident             | Big energy / Alpha vibes            |\n"
        "| Embarrassing          | Cringe                               |\n"
        "| Explanation           | The rundown                         |\n"
        "| Important person      | The real MVP                        |\n"
        "| Work hard             | Grind season / Hustle mode          |\n"
        "| Follow along          | Keep up with the vibe               |\n"
        "| Future                | Next-level moves                    |\n"
        "| Tell me               | Spill the tea / Drop the deets      |\n"
        "| Amazing person        | Legend / Real one                   |\n\n"
        "Example Conversions:\n"
        "- If the text explains a historical event:\n"
        "    - Original: 'The Industrial Revolution brought a wave of change in the manufacturing sector.'\n"
        "    - Gen Z Lingo: 'The Industrial Rev was basically humanity’s first big “glow up.” Picture it: factories popping off, machines going brrr, and the world going from chillin’ to hustle mode. This was the OG tech takeover.'\n\n"
        "- If the text is about science:\n"
        "    - Original: 'The theory of relativity by Einstein revolutionized physics.'\n"
        "    - Gen Z Lingo: 'Einstein, our physics GOAT, dropped relativity like it was hot. He had the ultimate brain-Riz, rewriting physics with that “time and space ain't what you think” vibe. Real ones know he’s the reason we got sci-fi movies on lock.'\n\n"
        "- If the text is about a mathematical concept:\n"
        "    - Original: 'To solve for x in this equation, isolate x on one side.'\n"
        "    - Gen Z Lingo: 'Alright, let’s talk solving for x, like sliding in DMs but math edition. You gotta single out x, like it’s that crush you’re finally making a move on. Isolate it and boom, answer’s yours.'\n\n"
        "The goal is to take the topic and give it a Gen Z makeover—keep it fun, relatable, and hype-worthy. Remember to add small tweaks to keep each response unique and lively."
        "Original Text:\n"
        f"{input_text.strip()}\n\n"
        "Transformed Text:"
    )

    payload = {
        "model": model_name,
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "max_tokens": 500,
        "temperature": 0.7
    }

    try:
        response = requests.post(OLLAMA_API_URL, headers=HEADERS, data=json.dumps(payload))
        response.raise_for_status()  # Raise an error for bad status codes

        response_data = response.json()
        if "choices" in response_data and len(response_data["choices"]) > 0:
            transformed_text = response_data["choices"][0].get("message", {}).get("content", "").strip()
            if not transformed_text:
                raise ValueError("No transformed text found in the API response.")
            return transformed_text
        else:
            raise ValueError("Invalid response structure from the API.")
    except (ValueError, json.JSONDecodeError) as e:
        print(f"Error parsing API response: {e}", file=sys.stderr)
        sys.exit(1)
    except requests.exceptions.RequestException as e:
        print(f"Error during API request: {e}", file=sys.stderr)
        sys.exit(1)

def write_output_file(file_path, content):
    """
    Writes the transformed content to the output file.

    Args:
        file_path (str): Path to the output text file.
        content (str): Transformed text to write.
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        print(f"Transformed text has been saved to '{file_path}'.")
    except IOError as e:
        print(f"Failed to write to '{file_path}': {e}", file=sys.stderr)
        sys.exit(1)

# ------------------------------
# Main Execution
# ------------------------------

def main():
    # Check if the specified model is installed
    if not check_model_installed(MODEL_NAME):
        print(f"Model '{MODEL_NAME}' is not installed. Please install it using 'ollama install {MODEL_NAME}'.", file=sys.stderr)
        sys.exit(1)

    # Transform the text
    transformed_text = transform_text(ORIGINAL_TEXT, MODEL_NAME)

    # Write the transformed text to the output file
    write_output_file(OUTPUT_FILE_PATH, transformed_text)

if __name__ == "__main__":
    main()