# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "pymupdf>=1.24",
# ]
# ///

from pathlib import Path
import pymupdf


INPUT = Path(
    "./1_[K.J.Engel,R.Nagel]_One Parameter semigroups for linear evolution equations.pdf"
)
OUTPUT = INPUT.with_name(INPUT.stem + "_toc.pdf")


# ------------------------------------------------------------
# 页码映射
#
# 已知：
#   Prelude = xvii = 17
#   PDF 物理第 16 页
#
# 所以前置罗马数字：
#   PDF页 = 罗马页码 - 1
#
# Front Matter 到 xxi = 21，
# 因此正文 printed page 1 位于 PDF 物理第 21 页：
#   PDF页 = 正文页码 + 20
# ------------------------------------------------------------

def front(page: int) -> int:
    """前置部分：罗马数字换成十进制以后传进来。"""
    return page - 1


def body(page: int) -> int:
    """正文/附录：书上阿拉伯数字页码 -> PDF 物理页码。"""
    return page + 20


toc = [
    # Front matter
    [1, "Preface", front(7)],
    [1, "Prelude", front(17)],

    # I
    [1, "I. Linear Dynamical Systems", body(1)],
    [2, "1. Cauchy’s Functional Equation", body(2)],
    [2, "2. Finite-Dimensional Systems: Matrix Semigroups", body(6)],
    [2, "3. Uniformly Continuous Operator Semigroups", body(14)],
    [2, "4. More Semigroups", body(24)],
    [3, "a. Multiplication Semigroups on C₀(Ω)", body(24)],
    [3, "b. Multiplication Semigroups on Lᵖ(Ω, μ)", body(30)],
    [3, "c. Translation Semigroups", body(33)],
    [2, "5. Strongly Continuous Semigroups", body(36)],
    [3, "a. Basic Properties", body(37)],
    [3, "b. Standard Constructions", body(42)],
    [2, "Notes", body(46)],

    # II
    [1, "II. Semigroups, Generators, and Resolvents", body(47)],
    [2, "1. Generators of Semigroups and Their Resolvents", body(48)],
    [2, "2. Examples Revisited", body(59)],
    [3, "a. Standard Constructions", body(59)],
    [3, "b. Standard Examples", body(65)],
    [2, "3. Hille–Yosida Generation Theorems", body(70)],
    [3, "a. Generation of Groups and Semigroups", body(71)],
    [3, "b. Dissipative Operators and Contraction Semigroups", body(82)],
    [3, "c. More Examples", body(89)],
    [2, "4. Special Classes of Semigroups", body(96)],
    [3, "a. Analytic Semigroups", body(96)],
    [3, "b. Differentiable Semigroups", body(109)],
    [3, "c. Eventually Norm-Continuous Semigroups", body(112)],
    [3, "d. Eventually Compact Semigroups", body(117)],
    [3, "e. Examples", body(120)],
    [2, "5. Interpolation and Extrapolation Spaces for Semigroups", body(123)],
    [3, "a. Sobolev Towers", body(124)],
    [3, "b. Favard and Abstract Hölder Spaces", body(129)],
    [3, "c. Fractional Powers", body(137)],
    [2, "6. Well-Posedness for Evolution Equations", body(145)],
    [2, "Notes", body(154)],

    # III
    [1, "III. Perturbation and Approximation of Semigroups", body(157)],
    [2, "1. Bounded Perturbations", body(157)],
    [2, "2. Perturbations of Contractive and Analytic Semigroups", body(169)],
    [2, "3. More Perturbations", body(182)],
    [3, "a. The Perturbation Theorem of Desch–Schappacher", body(182)],
    [3, "b. Comparison of Semigroups", body(192)],
    [3, "c. The Perturbation Theorem of Miyadera–Voigt", body(195)],
    [3, "d. Additive Versus Multiplicative Perturbations", body(201)],
    [2, "4. Trotter–Kato Approximation Theorems", body(205)],
    [3, "a. A Technical Tool: Pseudoresolvents", body(206)],
    [3, "b. The Approximation Theorems", body(209)],
    [3, "c. Examples", body(214)],
    [2, "5. Approximation Formulas", body(219)],
    [3, "a. Chernoff Product Formula", body(219)],
    [3, "b. Inversion Formulas", body(231)],
    [2, "Notes", body(236)],

    # IV
    [1, "IV. Spectral Theory for Semigroups and Generators", body(238)],
    [2, "1. Spectral Theory for Closed Operators", body(239)],
    [2, "2. Spectrum of Semigroups and Generators", body(250)],
    [3, "a. Basic Theory", body(250)],
    [3, "b. Spectrum of Induced Semigroups", body(259)],
    [3, "c. Spectrum of Periodic Semigroups", body(266)],
    [2, "3. Spectral Mapping Theorems", body(270)],
    [3, "a. Examples and Counterexamples", body(270)],
    [3, "b. Spectral Mapping Theorems for Semigroups", body(275)],
    [3, "c. Weak Spectral Mapping Theorem for Bounded Groups", body(283)],
    [2, "4. Spectral Theory and Perturbation", body(289)],
    [2, "Notes", body(293)],

    # V
    [1, "V. Asymptotics of Semigroups", body(295)],
    [2, "1. Stability and Hyperbolicity for Semigroups", body(296)],
    [3, "a. Stability Concepts", body(296)],
    [3, "b. Characterization of Uniform Exponential Stability", body(299)],
    [3, "c. Hyperbolic Decompositions", body(305)],
    [2, "2. Compact Semigroups", body(308)],
    [3, "a. General Semigroups", body(308)],
    [3, "b. Weakly Compact Semigroups", body(312)],
    [3, "c. Strongly Compact Semigroups", body(317)],
    [2, "3. Eventually Compact and Quasi-compact Semigroups", body(329)],
    [2, "4. Mean Ergodic Semigroups", body(337)],
    [2, "Notes", body(345)],

    # VI
    [1, "VI. Semigroups Everywhere", body(347)],
    [2, "1. Semigroups for Population Equations", body(348)],
    [3, "a. Semigroup Method for the Cell Equation", body(349)],
    [3, "b. Intermezzo on Positive Semigroups", body(353)],
    [3, "c. Asymptotics for the Cell Equation", body(358)],
    [3, "Notes", body(361)],

    [2, "2. Semigroups for the Transport Equation", body(361)],
    [3, "a. Solution Semigroup for the Reactor Problem", body(361)],
    [3, "b. Spectral and Asymptotic Behavior", body(364)],
    [3, "Notes", body(367)],

    [2, "3. Semigroups for Second-Order Cauchy Problems", body(367)],
    [3, "a. The State Space X = X₁ᴮ × X", body(369)],
    [3, "b. The State Space X = X × X", body(372)],
    [3, "c. The State Space X = X₁ᶜ × X", body(374)],
    [3, "Notes", body(382)],

    [2, "4. Semigroups for Ordinary Differential Operators", body(383)],
    [3, "a. Nondegenerate Operators on ℝ and ℝ₊", body(384)],
    [3, "b. Nondegenerate Operators on Bounded Intervals", body(388)],
    [3, "c. Degenerate Operators", body(390)],
    [3, "d. Analyticity of Degenerate Semigroups", body(400)],
    [3, "Notes", body(403)],

    [2, "5. Semigroups for Partial Differential Operators", body(404)],
    [3, "a. Notation and Preliminary Results", body(405)],
    [3, "b. Elliptic Differential Operators with Constant Coefficients", body(408)],
    [3, "c. Elliptic Differential Operators with Variable Coefficients", body(411)],
    [3, "Notes", body(419)],

    [2, "6. Semigroups for Delay Differential Equations", body(419)],
    [3, "a. Well-Posedness of Abstract Delay Differential Equations", body(420)],
    [3, "b. Regularity and Asymptotics", body(424)],
    [3, "c. Positivity for Delay Differential Equations", body(428)],
    [3, "Notes", body(435)],

    [2, "7. Semigroups for Volterra Equations", body(435)],
    [3, "a. Mild and Classical Solutions", body(436)],
    [3, "b. Optimal Regularity", body(442)],
    [3, "c. Integro-Differential Equations", body(447)],
    [3, "Notes", body(452)],

    [2, "8. Semigroups for Control Theory", body(452)],
    [3, "a. Controllability", body(456)],
    [3, "b. Observability", body(466)],
    [3, "c. Stabilizability and Detectability", body(468)],
    [3, "d. Transfer Functions and Stability", body(473)],
    [3, "Notes", body(476)],

    [2, "9. Semigroups for Nonautonomous Cauchy Problems", body(477)],
    [3, "a. Cauchy Problems and Evolution Families", body(477)],
    [3, "b. Evolution Semigroups", body(481)],
    [3, "c. Perturbation Theory", body(487)],
    [3, "d. Hyperbolic Evolution Families in the Parabolic Case", body(492)],
    [3, "Notes", body(496)],

    # VII
    [1, "VII. A Brief History of the Exponential Function", body(497)],
    [2, "1. A Bird’s-Eye View", body(497)],
    [2, "2. The Functional Equation", body(500)],
    [2, "3. The Differential Equation", body(502)],
    [2, "4. The Birth of Semigroup Theory", body(506)],

    # Appendix
    [1, "Appendix", body(509)],
    [2, "A. A Reminder of Some Functional Analysis", body(509)],
    [2, "B. A Reminder of Some Operator Theory", body(515)],
    [2, "C. Vector-Valued Integration", body(522)],
    [3, "a. The Bochner Integral", body(522)],
    [3, "b. The Fourier Transform", body(526)],
    [3, "c. The Laplace Transform", body(530)],

    # Epilogue
    [1, "Epilogue", body(531)],
    [2, "Determinism: Scenes from the Interplay Between Metaphysics and Mathematics", body(531)],
    [3, "1. The Mathematical Structure", body(533)],
    [3, "2. Are Relativity, Quantum Mechanics, and Chaos Deterministic?", body(536)],
    [3, "3. Determinism in Mathematical Science from Newton to Einstein", body(538)],
    [3, "4. Developments in the Concept of Object from Leibniz to Kant", body(546)],
    [3, "5. Back to Some Roots of Our Problem: Motion in History", body(549)],
    [3, "6. Bibliography and Further Reading", body(553)],

    # Back matter
    [1, "References", body(555)],
    [1, "List of Symbols and Abbreviations", body(577)],
    [1, "Index", body(580)],
]


def main():
    if not INPUT.exists():
        raise SystemExit(f"找不到 PDF：{INPUT}")

    doc = pymupdf.open(INPUT)

    print(f"PDF 总页数: {doc.page_count}")
    print(f"Prelude xvii -> PDF 第 {front(17)} 页")
    print(f"正文第 1 页 -> PDF 第 {body(1)} 页")
    print(f"Index 580 -> PDF 第 {body(580)} 页")

    # 简单检查，防止 offset 写错导致越界
    bad = [item for item in toc if item[2] < 1 or item[2] > doc.page_count]
    if bad:
        print("\n以下目录项超出 PDF 页数：")
        for item in bad:
            print(item)
        raise SystemExit("页码映射可能不正确，请检查 offset。")

    # 替换现有 outline / bookmarks
    doc.set_toc(toc)

    doc.save(
        OUTPUT,
        garbage=4,
        deflate=True,
    )
    doc.close()

    print(f"\n完成：{OUTPUT}")


if __name__ == "__main__":
    main()