# Task P.4.3 - PDF Runtime Refactoring (Regression-first)

## Objective

Implement the new section-based PDF runtime architecture designed in Task P.4.2.

This task is a **runtime refactor only**.

The primary objective is to replace the current page-index-driven runtime with the new section-based runtime **without changing the rendered output of existing templates**.

This task must not introduce new PDF layouts or Product Item pages yet.

---

# Prerequisites

Complete and reuse:

* Task P.4 Discovery
* Task P.4.1 Runtime Verification
* Task P.4.2 Runtime Design

Do not redesign the architecture.

Implement the approved design only.

---

# Primary Goal

Move from

```text
Hardcoded Page Index

↓

Topic Engine

↓

PDF
```

to

```text
Section-based Runtime

↓

Section Composer

↓

Template Assembler

↓

PDF
```

while maintaining identical output for all existing templates.

---

# Regression-first Rule

This task follows a strict Regression-first strategy.

Before introducing any new rendering capability:

* existing templates must continue producing identical PDFs
* preview, download and approved PDF must remain unchanged
* all regression tests must pass

Feature additions are intentionally deferred.

---

# Scope

Implement only runtime architecture.

Included

* runtime contracts
* compatibility adapter
* page resolver
* section composer
* render context
* topic engine refactor
* template assembler
* runtime diagnostics

Excluded

* Product Item page
* Product Item rendering
* new template JSON
* CRM Template UI
* user render options
* template version changes
* database changes

---

# Implementation Requirements

## Phase 1 — Runtime Contracts

Create runtime contracts.

At minimum

* SectionRole
* RenderContext
* ResolvedTemplate
* ResolvedPages
* BuiltSection
* RuntimeIssue
* AssembledTemplate

Responsibilities must match Task P.4.2.

---

## Phase 2 — Compatibility Adapter

Implement

TemplateCompatibilityAdapter

Responsibilities

* explicit marker support
* legacy marker inference
* normalize legacy templates
* expose Runtime Issues

Legacy templates must continue working without modification.

---

## Phase 3 — Page Resolver

Replace page-index assumptions.

The runtime must never depend on

```ts
schemas[1]
```

Responsibilities

* discover pages
* classify by SectionRole
* detect duplicates
* detect missing markers
* produce insertion anchors

---

## Phase 4 — Render Context

Introduce a shared runtime context.

Example

```ts
interface RenderContext {
    documentData;
    template;
    mappings;
    pages;
    policies;
    issues;
}
```

Every runtime component should consume RenderContext instead of receiving unrelated parameters.

The context must remain immutable where possible.

---

## Phase 5 — Section Registry

Implement a registry-based architecture.

Example

```ts
interface SectionBuilder {
    role: SectionRole;

    build(context: RenderContext): BuiltSection;
}
```

The runtime must discover builders through registration rather than hardcoded orchestration.

Section Composer must not know implementation details of builders.

---

## Phase 6 — Section Composer

Implement

SectionComposer

Responsibilities

* execute builders
* skip disabled sections
* collect Runtime Issues
* preserve logical order
* return assembled section outputs

The composer must not contain rendering logic.

---

## Phase 7 — Topic Engine Refactor

Refactor Topic Engine.

Current behavior

```text
Page Index

↓

Topic Engine
```

New behavior

```text
Resolved Page

↓

Topic Engine
```

The generated output must remain identical.

---

## Phase 8 — Template Assembler

Implement

TemplateAssembler

Responsibilities

* preserve existing pages
* assemble generated sections
* merge template inputs
* preserve page order
* return final template

No Product Item pages yet.

---

## Phase 9 — PDF Runtime Integration

Wire the new runtime into

* Preview
* Download
* Approved PDF

All three flows must use the same runtime.

No duplicated pipelines.

---

# Runtime Diagnostics

Implement RuntimeIssue collection.

Support

* MISSING_MARKER
* DUPLICATE_MARKER
* INVALID_TEMPLATE
* MISSING_MAPPING
* LEGACY_COMPAT_MODE

Diagnostics must be available during Preview for debugging.

---

# Backward Compatibility

Existing templates must continue working without modification.

Current

* ALLA
* ONVALLA

templates must render exactly as before.

No migration required.

---

# Refactoring Constraints

Do NOT

* modify template JSON
* introduce Product Item pages
* change template mappings
* modify database schema
* change API contracts
* change CRM Template UI

---

# Code Quality Requirements

* Single Responsibility Principle
* Dependency Injection where appropriate
* Immutable runtime contracts where practical
* No duplicated rendering logic
* No duplicated template resolution
* No duplicated mapping resolution
* Strong typing
* Comprehensive inline documentation for new runtime components

---

# Testing Requirements

Regression tests are mandatory.

Verify

## Runtime

* Preview
* Download
* Approved PDF

## Templates

* ALLA
* ONVALLA

## Rendering

* Topic rendering
* Signature placement
* Mapping resolution
* Pagination

Expected result

Rendered PDF must remain visually identical to the previous runtime.

---

# Deliverables

Implementation must include

* Runtime Contracts
* Compatibility Adapter
* Page Resolver
* RenderContext
* Section Registry
* Section Composer
* Refactored Topic Engine
* Template Assembler
* Runtime Diagnostics
* Updated Runtime Integration
* Regression Tests

---

# Acceptance Criteria

* No hardcoded page indexes remain.
* Runtime becomes section-based.
* Topic Engine no longer depends on page position.
* Legacy templates render without modification.
* Preview, Download and Approved PDF use one shared runtime.
* Existing PDF output remains unchanged.
* Runtime is ready for Product Item Engine implementation in Task P.4.4.
* No functional regression is introduced.

---

# Out of Scope

The following work belongs to later tasks:

**Task P.4.4**

* Product Item Engine
* Product Item pagination
* Product Item section rendering

**Task P.4.5**

* New PDF template versions
* Product Item template layout

**Task P.4.6**

* CRM Template integration
* Template activation
* Version publishing

**Task P.4.7**

* Render Policy configuration
* User-selectable section visibility
* Organization default rendering options

---

# Final Success Condition

At the end of Task P.4.3, the internal PDF runtime architecture shall be completely refactored to the new section-based design while producing identical output to the legacy runtime.

No new user-visible functionality is expected in this task. The success metric is architectural modernization with zero regression, providing a stable foundation for subsequent Product Item and optional section features.
