import os, hashlib
from django.conf import settings
from webapp.common import create_thumbnail_surat, create_thumbnail_word, update_tgl, create_thumbnail
from webapp.models import koleksi as m_koleksi
from django.utils.text import slugify


# Alias agar kode lama tetap bisa pakai nama create_thumbnail_surat
def create_thumbnail_surat(rel_path):
    return create_thumbnail(rel_path)


def deploy(request, pk_contents, files):
    """
    Simpan file baru dan soft-delete semua file aktif sebelumnya.
    """
    # Soft delete lampiran aktif
    m_koleksi.Attachments._update({'is_deleted': True}, {'pk_contents': pk_contents})

    for file in files:
        random_ = update_tgl()['tgldetik']

        attachment = m_koleksi.Attachments.objects.create(
            pk_contents=m_koleksi.Contents.objects.get(pk=pk_contents),
            name=file.name,
            size=file.size,
            _type=file.content_type,
            is_deleted=False  # Penting
        )

        # Path dan direktori
        # prefix = settings.FILE_DIR
        # infix = f"{attachment.created.year:04}/{attachment.created.month:02}/{attachment.created.day:02}"
        # filename = f"{random_}{hashlib.md5(os.path.splitext(file.name)[0].encode()).hexdigest()}{os.path.splitext(file.name)[1]}"
        # full_path = os.path.join(prefix, infix, filename)

        # Path dan direktori 
        prefix = settings.FILE_DIR
        infix = f"{attachment.created.year:04}/{attachment.created.month:02}/{attachment.created.day:02}"
        name, ext = os.path.splitext(file.name)
        filename = f"{attachment.pk}-{slugify(name)}{ext}"
        full_path = os.path.join(prefix, infix, filename)

        # Simpan ke disk
        os.makedirs(os.path.join(prefix, infix), exist_ok=True)
        with open(full_path, 'xb+') as buffer:
            for chunk in file.chunks():
                buffer.write(chunk)

        # Simpan path ke DB
        attachment.path = f"{infix}/{filename}"
        attachment.save()

        # Buat thumbnail sesuai jenis file
        ext = os.path.splitext(file.name)[1].lower()
        try:
            if ext == ".pdf":
                create_thumbnail_surat(attachment.path)  # alias → common.create_thumbnail

            elif ext in [".jpg", ".jpeg", ".png"]:
                # gambar langsung dipakai → tidak perlu bikin thumbnail lagi
                pass

            elif ext in [".docx", ".doc"]:
                create_thumbnail_word(attachment.path)  # langsung dari common.py

            else:
                print(f"ℹ️ Format {ext} tidak didukung thumbnail.")
        except Exception as e:
            print(f"❌ Gagal membuat thumbnail untuk {file.name}: {e}")

# def deploy(request, pk_contents, files):
#     """
#     Simpan file baru dan soft-delete semua file aktif sebelumnya.
#     """
#     # Soft delete lampiran aktif
#     m_koleksi.Attachments._update({'is_deleted': True}, {'pk_contents': pk_contents})

#     for file in files:
#         random_ = update_tgl()['tgldetik']

#         attachment = m_koleksi.Attachments.objects.create(
#             pk_contents=m_koleksi.Contents.objects.get(pk=pk_contents),
#             name=file.name,
#             size=file.size,
#             _type=file.content_type,
#             is_deleted=False  # Penting
#         )

#         # Path dan direktori
#         prefix = settings.FILE_DIR
#         infix = f"{attachment.created.year:04}/{attachment.created.month:02}/{attachment.created.day:02}"
#         filename = f"{random_}{hashlib.md5(os.path.splitext(file.name)[0].encode()).hexdigest()}{os.path.splitext(file.name)[1]}"
#         full_path = os.path.join(prefix, infix, filename)

#         # Simpan ke disk
#         os.makedirs(os.path.join(prefix, infix), exist_ok=True)
#         with open(full_path, 'xb+') as buffer:
#             for chunk in file.chunks():
#                 buffer.write(chunk)

#         # Simpan path ke DB
#         attachment.path = f"{infix}/{filename}"
#         attachment.save()

#         # Buat thumbnail sesuai jenis file
#         ext = os.path.splitext(file.name)[1].lower()
#         try:
#             if ext == ".pdf":
#                 create_thumbnail_surat(attachment.path)

#             elif ext in [".jpg", ".jpeg", ".png"]:
#                 # gambar langsung dipakai → tidak perlu bikin thumbnail lagi
#                 pass

#             elif ext in [".docx", ".doc"]:
#                 create_thumbnail_word(attachment.path)

#             else:
#                 print(f"ℹ️ Format {ext} tidak didukung thumbnail.")
#         except Exception as e:
#             print(f"❌ Gagal membuat thumbnail untuk {file.name}: {e}")


def destroy_one(pk):
    """Hapus 1 lampiran (soft-delete saja)."""
    m_koleksi.Attachments._update({'is_deleted': True}, {'pk': pk})


def destroy_many(pk_contents):
    """Soft delete semua lampiran dalam konten tertentu."""
    m_koleksi.Attachments._update({'is_deleted': True}, {'pk_contents': pk_contents})


def destroy_one_permanent(pk):
    """
    Hapus file dari disk + database (PERMANEN).
    Gunakan hanya jika yakin file tak dibutuhkan untuk rollback.
    """
    try:
        attachment = m_koleksi.Attachments.objects.get(pk=pk)
    except m_koleksi.Attachments.DoesNotExist:
        return  # Sudah tidak ada

    try:
        full_path = os.path.join(settings.FILE_DIR, attachment.path)
        if os.path.exists(full_path):
            os.remove(full_path)
    except Exception as e:
        print('❌ Gagal hapus file dari disk:', e)

    attachment.delete()
