#!/bin/python3

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

from PyPDF2 import PdfReader, PdfWriter
import sys
import os
import re
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from datetime import datetime
from get_strategy import gettext


from logger_config import get_logger

# 获取日志记录器
logger = get_logger()
def get_linux_fonts():
    """返回系统可用的中文和西文字体路径"""
    chinese_fonts = []
    latin_fonts = []

    # 中文字体优先 Noto Sans CJK / WenQuanYi Micro Hei
    possible_chinese = [
        "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
        "/usr/share/fonts/truetype/wenquanyi/WenQuanYiMicroHei.ttf",
        "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf"
    ]
    chinese_fonts = [f for f in possible_chinese if os.path.exists(f)]

    # 西文字体优先 LiberationSans / DejaVuSans
    possible_latin = [
        "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    ]
    latin_fonts = [f for f in possible_latin if os.path.exists(f)]

    return chinese_fonts, latin_fonts

def create_watermark(output_pdf, watermark_text, font_path=None, font_size=16, opacity=0.5,angle=45, spacing_scale=0.8, margin=0.2):
    try:
        chinese_fonts, latin_fonts = get_linux_fonts()

        if font_path:
            if not os.path.exists(font_path):
                raise RuntimeError(f"指定字体不存在: {font_path}")
            pdfmetrics.registerFont(TTFont("CustomFont", font_path))
            cjk_font = "CustomFont"
            latin_font = "CustomFont"
        else:
            # 注册中文字体
            if not chinese_fonts:
                raise RuntimeError("系统未找到可用中文字体")
            pdfmetrics.registerFont(TTFont("CJKFont", chinese_fonts[0]))
            cjk_font = "CJKFont"

            # 注册西文字体
            if not latin_fonts:
                raise RuntimeError("系统未找到可用西文字体")
            pdfmetrics.registerFont(TTFont("LatinFont", latin_fonts[0]))
            latin_font = "LatinFont"

        c = canvas.Canvas(output_pdf, pagesize=letter)
        width, height = letter
        c.setFillAlpha(opacity)

        # 拆分文本：中文按字符，英文按单词
        max_width = width - 2 * margin * inch
        lines, current_line = [], ""
        cur_width = 0

        tokens = re.findall(r'[\u2E80-\u9FFF\u3000-\u30FF]|[\w]+|\s', watermark_text)
        for token in tokens:
            font = cjk_font if re.match(r'[\u2E80-\u9FFF\u3000-\u30FF]', token) else latin_font
            token_width = pdfmetrics.stringWidth(token, font, font_size)
            if cur_width + token_width > max_width:
                lines.append(current_line)
                current_line = token
                cur_width = token_width
            else:
                current_line += token
                cur_width += token_width
        if current_line:
            lines.append(current_line)

        # 计算文本尺寸
        text_height = font_size * len(lines)
        text_width = max(
            sum(pdfmetrics.stringWidth(ch, cjk_font if re.match(r'[\u2E80-\u9FFF\u3000-\u30FF]', ch) else latin_font, font_size)
                for ch in line)
            for line in lines
        )

        spacing = max(text_width, text_height) * spacing_scale
        num_copies_x = int((width - 2 * margin * inch) / spacing) + 2
        num_copies_y = int((height - 2 * margin * inch) / spacing) + 2

        # 绘制水印
        for i in range(num_copies_x):
            for j in range(num_copies_y):
                x = margin * inch + i * spacing
                y = margin * inch + j * spacing

                c.saveState()
                c.translate(x, y)
                c.rotate(angle)

                for idx, line in enumerate(lines):
                    cur_x = 0
                    for ch in line:
                        font = cjk_font if re.match(r'[\u2E80-\u9FFF\u3000-\u30FF]', ch) else latin_font
                        c.setFont(font, font_size)
                        c.drawString(cur_x, -idx * font_size, ch)
                        cur_x += pdfmetrics.stringWidth(ch, font, font_size)

                c.restoreState()

        c.save()
        return output_pdf

    except Exception as e:
        logger.error(f"生成水印 PDF 时发生错误：{str(e)}")
        return None

def add_watermark(input_pdf, watermark_pdf, output_pdf):
    logger.debug("---add_watermark----")
    """
    将水印添加到目标 PDF 文件的每一页。
    
    :param input_pdf: 输入 PDF 文件路径
    :param watermark_pdf: 水印 PDF 文件路径
    :param output_pdf: 输出 PDF 文件路径
    """
    watermark_reader = PdfReader(watermark_pdf)
    watermark_page = watermark_reader.pages[0]

    reader = PdfReader(input_pdf)
    writer = PdfWriter()

    # 合并水印到每一页
    for page_number in range(len(reader.pages)):
        page = reader.pages[page_number]
        page.merge_page(watermark_page)  # 合并水印页面
        writer.add_page(page)

    # 写入最终的 PDF
    # with open(output_pdf, "wb") as output_file:
    #     logger.debug(f"调试：--output_pdf is::=====： {output_pdf}")
    #     writer.write(output_file)

    # 检查并创建 tmp 目录
    dir_path = os.path.dirname(output_pdf)
    tmp_dir = os.path.join(dir_path, "tmp")
    os.makedirs(tmp_dir, exist_ok=True)  # 创建 tmp 目录，如果已存在则忽略

    # 构建新的文件路径
    filename = os.path.basename(output_pdf)
    new_output_pdf = os.path.join(tmp_dir, filename)

    # 尝试写入文件
    try:
        with open(new_output_pdf, "wb") as output_file:
            writer.write(output_file)
        logger.debug(f"文件已成功写入: {new_output_pdf}")
    except PermissionError:
        logger.debug(f"错误：没有权限写入文件 {new_output_pdf}。")
    return new_output_pdf


def printer_watermark(filepath, username):
    # 示例使用
    # font_path = "/usr/share/fonts/kyfonts/STSONG.TTF"
    input_pdf = sys.argv[1] #filepath #"./input.pdf"
    watermark_pdf = "/opt/watermark-control/watermarks/watermark.pdf" # "/opt/watermark-control/watermarks/watermark.pdf"
    
    output_pdf = sys.argv[1] #"/home/zy-arm/practice/demos/waterMark/out-cups.pdf" #"output-cups.pdf"
    # 获取当前时间，格式化为字符串（例如：YYYY-MM-DD_HH-MM-SS）
    # dataTime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    # watermark_param = f"{username}{dataTime}"

    strategy_text = gettext(username)
    
    logger.debug(f"strategy_text: {strategy_text}")

    # 创建中文水印 PDF（包含多个水印副本）
    watermarked_pdf = create_watermark(watermark_pdf, strategy_text,font_size=16,opacity=0.5,angle=30,spacing_scale=0.8,margin=0.2)

    logger.debug(f"水印文本地址: {watermarked_pdf}")
    
    # 将水印添加到目标 PDF
    newpath = add_watermark(input_pdf, watermarked_pdf, output_pdf)
    return newpath


# 判断是否是pdf文件
def is_pdf_file(file_path):
    try:
        with open(file_path, 'rb') as f:
            PdfReader(f)
        return True
    except Exception as e:
        return False





if __name__ == '__main__':
    if len(sys.argv) > 1 and  (filepath := sys.argv[1]) and (username := sys.argv[2]) and is_pdf_file(filepath):
        print(printer_watermark(filepath, username))

