#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF标准化脚本
将PDF标准化为A4尺寸（210mm x 297mm 或 297mm x 210mm）
"""

import fitz  # PyMuPDF
import sys
import os
import io

# 设置标准输出编码为UTF-8（解决Windows GBK编码问题）
if sys.platform == 'win32':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')


def normalize_pdf_to_a4(input_pdf, output_pdf, preserve_orientation=True, first_page_only=False):
    """
    将PDF标准化为A4尺寸

    参数:
        input_pdf: 输入PDF路径
        output_pdf: 输出PDF路径
        preserve_orientation: 保留原始方向；False = 强制竖向（横向页面旋转90°）
        first_page_only: 只保留第一页

    返回:
        成功返回True，失败返回False
    """
    try:
        # A4尺寸（points，1 point = 1/72 inch）
        A4_WIDTH = 595.0   # 210mm
        A4_HEIGHT = 842.0  # 297mm

        doc = fitz.open(input_pdf)
        new_doc = fitz.open()

        page_range = range(1) if first_page_only else range(len(doc))
        for page_num in page_range:
            page = doc[page_num]

            original_rect = page.rect
            original_width = original_rect.width
            original_height = original_rect.height

            is_landscape = original_width > original_height

            if preserve_orientation and is_landscape:
                target_width = A4_HEIGHT   # 842
                target_height = A4_WIDTH   # 595
            else:
                target_width = A4_WIDTH    # 595
                target_height = A4_HEIGHT  # 842

            new_page = new_doc.new_page(width=target_width, height=target_height)

            if not preserve_orientation and is_landscape:
                # 横向页面旋转90°变竖向：旋转后有效宽高互换
                effective_w = original_height
                effective_h = original_width
                scale = min(target_width / effective_w, target_height / effective_h)
                scaled_w = effective_w * scale
                scaled_h = effective_h * scale
                x_offset = (target_width - scaled_w) / 2
                y_offset = (target_height - scaled_h) / 2
                content_rect = fitz.Rect(x_offset, y_offset, x_offset + scaled_w, y_offset + scaled_h)
                new_page.show_pdf_page(content_rect, doc, page_num, rotate=90)
            else:
                scale_x = target_width / original_width
                scale_y = target_height / original_height
                scale = min(scale_x, scale_y)
                scaled_width = original_width * scale
                scaled_height = original_height * scale
                x_offset = (target_width - scaled_width) / 2
                y_offset = (target_height - scaled_height) / 2
                content_rect = fitz.Rect(x_offset, y_offset, x_offset + scaled_width, y_offset + scaled_height)
                new_page.show_pdf_page(content_rect, doc, page_num)

        doc.close()

        if os.path.exists(output_pdf):
            try:
                os.remove(output_pdf)
            except Exception as e:
                print(f"WARNING: Cannot remove existing file: {e}", file=sys.stderr)
                import tempfile
                temp_fd, temp_path = tempfile.mkstemp(suffix='.pdf', dir=os.path.dirname(output_pdf))
                os.close(temp_fd)
                output_pdf = temp_path

        new_doc.save(output_pdf, garbage=4, deflate=True)
        new_doc.close()

        print("SUCCESS: PDF normalized to A4")
        return True

    except Exception as e:
        print(f"ERROR: {str(e)}", file=sys.stderr)
        import traceback
        traceback.print_exc(file=sys.stderr)
        return False


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python normalize_pdf.py <input_pdf> <output_pdf> [preserve_orientation] [first_page_only]")
        sys.exit(1)

    input_pdf = sys.argv[1]
    output_pdf = sys.argv[2]
    preserve_orientation = True if len(sys.argv) <= 3 else (sys.argv[3] == '1')
    first_page_only = False if len(sys.argv) <= 4 else (sys.argv[4] == '1')

    if not os.path.exists(input_pdf):
        print(f"ERROR: Input file not found: {input_pdf}", file=sys.stderr)
        sys.exit(1)

    success = normalize_pdf_to_a4(input_pdf, output_pdf, preserve_orientation, first_page_only)
    sys.exit(0 if success else 1)
