import os, json
from abc import ABCMeta
from config import prompt_settings

class Prompt():
    prompt_name : str # ex) marketing_prompt
    prompt_template_path : str #프롬프트 경로
    prompt_template : str # fstring 포맷
    prompt_input : list
    prompt_output : dict
    prompt_model : str
              
    def __init__(self, prompt_name, prompt_template_path):
        self.prompt_name = prompt_name
        self.prompt_template_path = prompt_template_path
        self.prompt_template, prompt_dict = self.read_prompt()
        self.prompt_input = prompt_dict['prompt_variables']
        self.prompt_output = prompt_dict['output_format']
        self.prompt_model = prompt_dict.get('model', "gpt-5-mini") 

    def _reload_prompt(self):
        self.prompt_template, prompt_dict = self.read_prompt()
        self.prompt_input = prompt_dict['prompt_variables']
        self.prompt_output = prompt_dict['output_format']
        self.prompt_model = prompt_dict.get('model', "gpt-5-mini") 

    def read_prompt(self) -> tuple[str, dict]:
        template_text_path = self.prompt_template_path + ".txt"
        prompt_dict_path = self.prompt_template_path + ".json"
        with open(template_text_path, "r") as fp:
            prompt_template = fp.read()
        with open(prompt_dict_path, "r") as fp:
            prompt_dict = json.load(fp)

        return prompt_template, prompt_dict

    def build_prompt(self, input_data:dict) -> str:
        self.check_input(input_data)
        build_template = self.prompt_template
        print("build_template", build_template)
        print("input_data", input_data)
        build_template = build_template.format(**input_data)
        return build_template
          
    def check_input(self, input_data:dict) -> bool:
        missing_variables = input_data.keys() - set(self.prompt_input)
        if missing_variables:
            raise Exception(f"missing_variable for prompt {self.prompt_name} : {missing_variables}")

        flooding_variables = set(self.prompt_input) - input_data.keys()
        if flooding_variables:
            raise Exception(f"flooding_variables for prompt {self.prompt_name} : {flooding_variables}")
        return True
    
marketing_prompt = Prompt(
    prompt_name=prompt_settings.MARKETING_PROMPT_NAME,
    prompt_template_path=os.path.join(prompt_settings.PROMPT_FOLDER_ROOT, prompt_settings.MARKETING_PROMPT_NAME)
)

summarize_prompt = Prompt(
    prompt_name=prompt_settings.SUMMARIZE_PROMPT_NAME,
    prompt_template_path=os.path.join(prompt_settings.PROMPT_FOLDER_ROOT, prompt_settings.SUMMARIZE_PROMPT_NAME)
)

lyric_prompt = Prompt(
    prompt_name=prompt_settings.LYLIC_PROMPT_NAME,
    prompt_template_path=os.path.join(prompt_settings.PROMPT_FOLDER_ROOT, prompt_settings.LYLIC_PROMPT_NAME)
)

def reload_all_prompt():
    marketing_prompt._reload_prompt()
    summarize_prompt._reload_prompt()
    lyric_prompt._reload_prompt()