from extensions import  db
from models.doc_manager import DocConfig
from models.ai_model import AITaskModelConfig, Balance, OpenAIModel, PromptType, SystemPrompt, ModelType

from config import DEFULT_TEXT_2_VOICE_MODEL_NAME, DEFULT_TEXT_MODEL_NAME, DEFULT_TEXT_STREAM_MODEL_NAME, DEFULT_VOICE_2_TEXT_MODEL_NAME, generator_openai_models
from services.prompt import CONVERSATIONAL_TTS_PROMPT, REFERENCES, STRUCTURED_ANS_PROMPT, SYSTEM_PROMPT, TEXT_TO_SPEECH  # dict

def seed_openai_models():
    added = 0

    # Iterate over the dict
    for name, info in generator_openai_models().items():
        exists = OpenAIModel.query.filter_by(name=name).first()
        if not exists:
            db.session.add(
                OpenAIModel(
                    name=name,
                    input_cost_per_1m=info["input_cost_per_1m"],
                    output_cost_per_1m=info["output_cost_per_1m"],
                    model_type=info["model_type"],
                    supports_temperature = info["supports_temperature"],
                    supports_web_search = info["supports_web_search"]

                )
            )
            added += 1

    db.session.commit()
    print(f"{added} OpenAI models seeded successfully")


def seed_prompts():
    added = 0

    defaults = {
        PromptType.TEXT: SYSTEM_PROMPT ,
        PromptType.ANSWER_STRUCT: STRUCTURED_ANS_PROMPT ,
        PromptType.TEXT_TO_VOICE: TEXT_TO_SPEECH,
        PromptType.CONVERSATION: CONVERSATIONAL_TTS_PROMPT,
        PromptType.REFERENCES : REFERENCES
    }

    for ptype, content in defaults.items():
        if not SystemPrompt.query.filter_by(type=ptype).first():
            db.session.add(SystemPrompt(
                type=ptype,
                content=content
            ))

            added += 1


    db.session.commit()


    print(f"{added} Prompts seeded successfully")


def seed_balance():
    # check if a row already exists
    if not Balance.query.first():  # no row yet
        db.session.add(
            Balance(
                initial_charge_usd=100.0,
                remaining_balance_usd=100.0
            )
        )
        db.session.commit()
        print("Balance Prompts seeded successfully")
    else:
        print(" Balance row already exists, skipping seed")



def seed_doc_config():
    # check if a row already exists
    if not DocConfig.query.first():  # no row yet
        db.session.add(
            DocConfig(
                cache_lifetime=7,
                chunk_size=500,
                chunk_overlap=2,
                batch_size=32,
                top_k=20,
            )
        )
        db.session.commit()
        print("Doc Config seeded successfully")
    else:
        print("Doc Config row already exists, skipping seed")







def seed_task_model_configs():
    """Seed تنظیمات پیش‌فرض مدل‌ها برای هر نوع وظیفه (فقط در صورتی که هیچ تنظیماتی وجود نداشته باشد)"""
    
    # بررسی وجود هرگونه تنظیمات
    existing_config = AITaskModelConfig.query.first()
    
    if existing_config:
        print(" Task model configs already exist, skipping seed...")
        print("   Use force_seed_task_model_configs() to override existing configs")
        return
    
    # دریافت مدل‌های مورد نیاز
    text_model = OpenAIModel.query.filter_by(name=DEFULT_TEXT_MODEL_NAME).first()
    text_stream_model = OpenAIModel.query.filter_by(name=DEFULT_TEXT_STREAM_MODEL_NAME).first()
    text_to_voice_model = OpenAIModel.query.filter_by(name=DEFULT_TEXT_2_VOICE_MODEL_NAME).first()
    voice_to_text_model = OpenAIModel.query.filter_by(name=DEFULT_VOICE_2_TEXT_MODEL_NAME).first()
    text_to_voice_model = OpenAIModel.query.filter_by(name=DEFULT_TEXT_2_VOICE_MODEL_NAME).first()
    
    
    # اگر مدل‌های خاص پیدا نشدند، از اولین مدل موجود استفاده کن
    if not text_model:
        text_model = OpenAIModel.query.first()
        if text_model:
            print(f"    Default text model '{DEFULT_TEXT_MODEL_NAME}' not found, using '{text_model.name}' instead")

    if not text_stream_model:
        text_stream_model = OpenAIModel.query.first()
        if text_stream_model:
            print(f"    Default text stream model '{DEFULT_TEXT_MODEL_NAME}' not found, using '{text_stream_model.name}' instead")
    
    if not voice_to_text_model:
        voice_to_text_model = OpenAIModel.query.first()
        if voice_to_text_model:
            print(f"    Default voice-to-text model '{DEFULT_VOICE_2_TEXT_MODEL_NAME}' not found, using '{voice_to_text_model.name}' instead")
    
    if not text_to_voice_model:
        text_to_voice_model = OpenAIModel.query.first()
        if text_to_voice_model:
            print(f"    Default text-to-voice model '{DEFULT_TEXT_2_VOICE_MODEL_NAME}' not found, using '{text_to_voice_model.name}' instead")
    
    # ایجاد تنظیمات جدید (بدون غیرفعال کردن قبلی چون قبلی وجود ندارد)
    config = AITaskModelConfig(
        text_model_id=text_model.id if text_model else None,
        text_stream_model_id=text_stream_model.id if text_stream_model else None,
        voice_to_text_model_id=voice_to_text_model.id if voice_to_text_model else None,
        text_to_voice_model_id=text_to_voice_model.id if text_to_voice_model else None,
        is_active=True
    )
    
    db.session.add(config)
    db.session.commit()
    
    print(" Task model configs seeded successfully")
    print("=" * 40)
    print(f" Text Model: {text_model.name if text_model else 'None'}")
    print(f" Voice to Text Model: {voice_to_text_model.name if voice_to_text_model else 'None'}")
    print(f" Text to Voice Model: {text_to_voice_model.name if text_to_voice_model else 'None'}")
    print("=" * 40)




# -----------------------------------------------------------------------------------------------------------------------
def auto_seeds():
    seed_openai_models()
    seed_prompts()
    seed_balance()
    seed_doc_config()
    seed_task_model_configs()


if __name__ == "__main__":
    from app import create_app
    app = create_app()
    with app.app_context():
        auto_seeds()
