import json
import os
import threading
import time

from pilot.job.impl.base_job import BaseJob

from pilot.generater.vera import VeraSingleton

class GenerateTextBaseJob(BaseJob):

    prompt_content: str
    result_content: str
    result_file_path: str
    result_extension = '.md'
    stream = False

    def run(self):
        prompt = self.prompt_content
        if prompt is None or prompt == '':
            prompt = self.get_file_content()
        if self.result_file_path is None:
            self.result_file_path = self.get_new_extension_file_path(self.file_path, self.result_extension)
        # トークン数チェック
        vera_ai = VeraSingleton.get_instance()
        #token_count = vertexai.count_tokens(prompt)
        #if token_count == 0:
        #    super().run()
        #    return
        #if token_count > 900000:
        #    print(f"警告: promptのトークン数が900000を超えています ({token_count} tokens)")
        #    super().run()
        #    return
        # VertexAI で生成
        start = time.time()
        result = vera_ai.generate_content(prompt,stream=self.stream)
        end = time.time()
        print(f"AI 処理時間 {self.file_path}: {end - start:.2f}秒")
        self.result_content = result.get('response', '')

        with open(self.result_file_path, 'w', encoding='utf-8') as f:
            f.write(self.result_content)
        super().run()