#!/usr/bin/env python3
# ==============================================================================
# This script was generated by Google AI under the guidance of Mathieu Baudier.
#
# Changelog:
# - 2026-06-09: Original script generation with automated parameter extraction.
# 
# This library is free software; you can redistribute it and/or modify it under 
# the terms of the GNU Lesser General Public License as published by the Free 
# Software Foundation; either version 2.1 of the License, or (at your option) 
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT 
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 
# details.
# ==============================================================================

import sys
import json
import types
from datetime import datetime
from jinja2 import Environment, FunctionLoader

# 1. Parse 'key=value' terminal arguments dynamically
context = {}
for arg in sys.argv[1:]:
    if '=' in arg:
        key, value = arg.split('=', 1)
        
        # Check if the value looks like a JSON array or object
        if value.strip().startswith(('[', '{')):
            try: 
                context[key] = json.loads(value)
#                print(f"✅ Success | Key: '{key}' parsed as JSON -> Value: {context[key]} (Type: {type(context[key]).__name__})", file=sys.stderr)
            except json.JSONDecodeError as error: 
                # Fallback to raw string, routing error details to stderr
                context[key] = value
#                print(f"❌ JSON Error | Key: '{key}' failed to parse as JSON. Falling back to raw string.", file=sys.stderr)
#                print(f"   ↳ Faulty String: {value}", file=sys.stderr)
#                print(f"   ↳ Error Reason : {error.msg} at line {error.lineno}, column {error.colno}\n", file=sys.stderr)
        else:
            # Handle booleans and standard strings
            if value.lower() == 'true': 
                context[key] = True
            elif value.lower() == 'false': 
                context[key] = False
            else: 
                context[key] = value
#            print(f"📦 Standard | Key: '{key}' -> Value: {context[key]} (Type: {type(context[key]).__name__})", file=sys.stderr)

# 2. Read the GGUF template from standard input
template_content = sys.stdin.read()

# 3. Setup Hardened Template Environment with loop extensions loaded
env = Environment(
    loader=FunctionLoader(lambda name: template_content),
    keep_trailing_newline=True,
    extensions=['jinja2.ext.loopcontrols']
)

# 4. Universal GGUF Feature Compatibility Layer
def safe_tojson(obj, **kwargs):
    if isinstance(obj, (types.GeneratorType, map, filter)):
        obj = list(obj)
    ensure_ascii = False if 'ensure_ascii' not in kwargs else kwargs['ensure_ascii']
    return json.dumps(obj, ensure_ascii=ensure_ascii)

env.filters['tojson'] = safe_tojson
env.globals['strftime_now'] = lambda fmt: datetime.now().strftime(fmt)
env.globals['bos_token'] = context.get('bos_token', '<s>')
env.globals['eos_token'] = context.get('eos_token', '</s>')

def jinja_raise_exception(msg):
    raise Exception(f"JinjaTemplateError: {msg}")
env.globals['raise_exception'] = jinja_raise_exception

# 5. Compile the template 
template = env.get_template('gguf_template')

# 6. Dynamic Macro Exposure Layer
macro_context = template.new_context(context)
self_template = macro_context.parent.get('self')

if self_template:
    for macro_name in dir(self_template):
        if not macro_name.startswith('_'):
            macro_func = getattr(self_template, macro_name)
            if callable(macro_func):
                env.globals[macro_name] = macro_func

# 7. Render the template text
rendered_output = template.render(**context)

# 8. Output directly to stdout without appending implicit python newlines
sys.stdout.write(rendered_output)
sys.stdout.flush()
