from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from PyPDF2 import PdfReader, PdfWriter
from datetime import datetime, timedelta
import random
import os
import uuid

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FONT_DIR = os.path.join(BASE_DIR, "../assets/fonts")


def generate_livin_pdf(data, template_path, output_path):
    from reportlab.lib.colors import HexColor
    TEMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../static/tmp")
    os.makedirs(TEMP_DIR, exist_ok=True)

    packet_path = os.path.join(TEMP_DIR, f"temp_overlay_{uuid.uuid4().hex}.pdf")

    c = canvas.Canvas(packet_path)

    # tahoma
    FONT_TAHOMA = os.path.join(FONT_DIR, "tahoma.ttf")
    # tahomabd
    FONT_TAHOMA_BOLD = os.path.join(FONT_DIR, "tahomabd.ttf")
    # tahoma-italic
    FONT_TAHOMA_ITALIC = os.path.join(FONT_DIR, "tahoma-italic.ttf")
    # Tahoma-Faux-Italic
    FONT_TAHOMA_FAUX_ITALIC = os.path.join(FONT_DIR, "Tahoma-Faux-Italic.ttf")
    # tahomaitalic-lgzp5
    FONT_TAHOMA_ITALIC_LGZP5 = os.path.join(FONT_DIR, "tahomaitalic-lgzp5.ttf")

    pdfmetrics.registerFont(TTFont("Tahoma", FONT_TAHOMA))
    pdfmetrics.registerFont(TTFont("Tahoma-Bold", FONT_TAHOMA_BOLD))
    pdfmetrics.registerFont(TTFont("Tahoma-Italic", FONT_TAHOMA_ITALIC))
    pdfmetrics.registerFont(TTFont("Tahoma-Faux-Italic", FONT_TAHOMA_FAUX_ITALIC))
    pdfmetrics.registerFont(TTFont("Tahoma-Italic-LGZP5", FONT_TAHOMA_ITALIC_LGZP5))

    # --- Data ---
    cabang = data["cabang"]
    nama = data["nama"]
    
    # Tanggal random dari 3 bulan ke belakang
    now = datetime.now()
    # List 3 bulan ke belakang (misal: Juli 2025 -> [4, 5, 6] = April, Mei, Juni)
    bulan_list = [(now.month - i - 1) % 12 + 1 for i in range(3)]
    tahun_list = [now.year if now.month - i - 1 >= 0 else now.year - 1 for i in range(3)]

    bulan_list = [(now.month - i - 1) % 12 + 1 for i in range(1, 4)]
    tahun_list = [now.year if now.month - i - 1 >= 0 else now.year - 1 for i in range(1, 4)]
    print("Bulan List:", bulan_list)

    # Pilih salah satu bulan dan tahun secara acak
    idx = random.randint(0, 2)
    bulan_target = bulan_list[idx]
    tahun_target = tahun_list[idx]

    awal = datetime(tahun_target, bulan_target, 1)
    # Cari akhir bulan target
    if bulan_target == 12:
        akhir = datetime(tahun_target + 1, 1, 1) - timedelta(days=1)
    else:
        akhir = datetime(tahun_target, bulan_target + 1, 1) - timedelta(days=1)
   
    # format bulan ada Feb bukan FEB
    periode_awal_str = f"{awal.day:02d} {awal.strftime('%b')} {awal.year}"
    periode_akhir_str = f"{akhir.day:02d} {akhir.strftime('%b')} {akhir.year}"
    periode = periode_awal_str + " - " + periode_akhir_str 

    halaman = f"{random.randint(2, 9)}"

    # --- Draw ke PDF ---
    c.setFont("Tahoma", 8.2)
    c.setFillColor(HexColor("#000000"))
    c.drawString(122, 736, nama)
    c.drawString(339, 736, periode)

    c.setFont("Tahoma-Bold", 8.2)
    c.drawString(532, 736, halaman + ' dari ' + halaman)

    c.setFont("Tahoma", 8.2)
    c.drawString(122, 714, cabang)
    c.drawString(339, 714, periode_akhir_str)
    
    c.setFont("Tahoma-Faux-Italic", 8.2)
    c.drawString(544, 726, halaman + ' of ' + halaman)

    c.save()

    background = PdfReader(template_path)
    overlay = PdfReader(packet_path)
    writer = PdfWriter()

    page = background.pages[0]
    page.merge_page(overlay.pages[0])
    writer.add_page(page)

    with open(output_path, "wb") as f:
        writer.write(f)

    # Bersihkan file sementara
    if os.path.exists(packet_path):
        os.remove(packet_path)
