"""A terminal chat with explicit conversation history."""
import os
from urllib.error import URLError
from common import request_json


def main():
    messages = [{'role': 'system', 'content': 'Answer clearly. If you do not know, say so.'}]
    print('Type /reset to clear history or /quit to exit.')
    while True:
        try:
            question = input('You: ').strip()
        except (EOFError, KeyboardInterrupt):
            break
        if question == '/quit':
            break
        if question == '/reset':
            messages = messages[:1]
            print('History cleared.')
            continue
        if not question:
            continue
        pending = messages + [{'role': 'user', 'content': question}]
        try:
            response = request_json('chat', {
                'model': os.getenv('BLOG_CHAT_MODEL', 'qwen3:4b-instruct'),
                'messages': pending, 'stream': False,
                'options': {'num_ctx': 4096, 'num_predict': 400},
            })
        except (URLError, TimeoutError) as error:
            # Keep the saved history unchanged so the question can be asked again.
            print(f'Request failed ({error}). Is Ollama running? Nothing was added to the history.')
            continue
        message = response['message']
        messages = pending + [message]
        print('Assistant:', message['content'])
        if response.get('done_reason') == 'length':
            print('[Reply stopped at the num_predict limit.]')


if __name__ == '__main__':
    main()
