from peewee import *
from pathlib import Path

# Garante pasta de dados
data_dir = Path('/app/data')
data_dir.mkdir(parents=True, exist_ok=True)

db = SqliteDatabase(str(data_dir / 'cleiflow.db'))

class BaseModel(Model):
    class Meta:
        database = db

class AppConfig(BaseModel):
    key = CharField(unique=True)
    value = TextField()

    @classmethod
    def get_val(cls, key, default=''):
        try:
            return cls.get(cls.key == key).value
        except:
            return default

    @classmethod
    def set_val(cls, key, value):
        cls.replace(key=key, value=value).execute()

class Category(BaseModel):
    name = CharField(unique=True)
    target_path = CharField()
    match_keywords = CharField(null=True)
    content_type = CharField(default='mixed') 
    genre_filters = CharField(null=True)   
    country_filters = CharField(null=True) 

class FFmpegProfile(BaseModel):
    name = CharField()
    # Configuração de Codec
    video_codec = CharField(default='h264_vaapi')
    preset = CharField(default='medium')
    crf = IntegerField(default=23)
    
    # Configuração de Hardware (NOVO)
    hardware_type = CharField(default='vaapi') # vaapi, nvenc, qsv, cpu
    hybrid_decode = BooleanField(default=False) # Fix para Intel antigo (CPU Decode -> GPU Encode)
    
    # Áudio/Legenda
    audio_langs = CharField(default='por,eng,jpn')
    subtitle_langs = CharField(default='por')
    is_active = BooleanField(default=False)

def init_db():
    if db.is_closed():
        db.connect()
    
    db.create_tables([AppConfig, Category, FFmpegProfile], safe=True)
    
    # --- MIGRAÇÕES DE BANCO (Adiciona colunas se não existirem) ---
    try: db.execute_sql('ALTER TABLE category ADD COLUMN content_type VARCHAR DEFAULT "mixed"')
    except: pass
    try: db.execute_sql('ALTER TABLE category ADD COLUMN genre_filters VARCHAR DEFAULT ""')
    except: pass
    try: db.execute_sql('ALTER TABLE category ADD COLUMN country_filters VARCHAR DEFAULT ""')
    except: pass
    
    # Migração FFmpeg (Hardware Type)
    try: 
        db.execute_sql('ALTER TABLE ffmpegprofile ADD COLUMN hardware_type VARCHAR DEFAULT "vaapi"')
        db.execute_sql('ALTER TABLE ffmpegprofile ADD COLUMN hybrid_decode BOOLEAN DEFAULT 0')
    except: pass
    
    # Perfil padrão se estiver vazio
    if FFmpegProfile.select().count() == 0:
        FFmpegProfile.create(
            name="Padrão VAAPI (Intel/AMD)", 
            video_codec="h264_vaapi", 
            hardware_type="vaapi",
            hybrid_decode=False, # Padrão para hardware novo
            is_active=True
        )