InsuranceParse → Extract

Auto Insurance Declaration Page Extractor

Extracts policyholder details, premiums, drivers, vehicles, and coverage limits from auto insurance declarations.

Ship it with Extend

Live pipeline

a real document, processed end to end · view only
Source documentfarmers_sample (1).pdf

Step-by-step

An auto insurance declaration page is a summary document issued by an insurance company that outlines active policy details including coverage types with limits and deductibles, insured vehicles with identification numbers, named drivers, effective and expiration dates, premiums, and applicable discounts. This template takes in Auto Insurance Declaration Pages and outputs markdown (.md) capturing the declaration page's full text and layout, and JSON (.json) with structured policy fields including vehicles, coverages, drivers, rating information, and premium totals per the extraction schema by using Extend's Parse, Extract primitives.

Input
Auto Insurance Declaration Pages
Compatible document types (full list)
.pdf.docx.xlsx.png.jpg.jpeg.tiff.tif.svg.heic.heif.bmp.gif.webp.psd.xls.xltm.xltx.ods.doc.wpd.dotx.odt.pptx.ppt.ppm.csv.txt.html.xml.rtf.lis.md.eml.pcx
Step 1

Parse

Converts the document into clean, layout-aware markdown plus structured blocks with spatial metadata.

InputSource document — PDF, image, spreadsheet, presentation, or scan
Config
blockOptions.text.agentic.enabledtruechanged
chunkingStrategy.type"document"
engine"parse_performance"
OutputMarkdown chunked by page or section, plus typed blocks (text, table, figure) with bounding boxes

You can learn more about Parse configuration in Extend's Parse documentation.

Step 2

Extract

Pulls a defined set of fields from the document and returns them as structured JSON matching a schema.

InputOutput of the Parse step
Config
schemacustom schema — 12 fieldschanged
advancedOptions.advancedMultimodalEnabledtruechanged
advancedOptions.reviewAgent.enabledtruechanged
baseProcessor"extraction_performance"
OutputJSON shaped to the extraction schema, with per-field confidence scores and citations grounding each value to its source location

You can learn more about Extract configuration in Extend's Extract documentation.

Example code

{
  "name": "Auto Insurance Declaration Page Processing Pipeline",
  "steps": [
    {
      "name": "startTrigger1",
      "type": "TRIGGER",
      "next": [
        {
          "step": "parse1"
        }
      ]
    },
    {
      "name": "parse1",
      "type": "PARSE",
      "config": {
        "parseConfig": {
          "blockOptions": {
            "text": {
              "agentic": {
                "enabled": true
              }
            }
          },
          "chunkingStrategy": {
            "type": "document"
          }
        }
      },
      "next": [
        {
          "step": "extraction2"
        }
      ]
    },
    {
      "name": "extraction2",
      "type": "EXTRACT",
      "config": {
        "extractorConfig": {
          "schema": {
            "type": "object",
            "required": [
              "vehicles",
              "coverages",
              "discounts",
              "total_fees",
              "named_drivers",
              "policy_number",
              "rating_information",
              "total_policy_premium",
              "policy_effective_date",
              "insurance_company_name",
              "policy_expiration_date",
              "total_policy_premium_and_fees"
            ],
            "properties": {
              "vehicles": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "vin",
                    "coverages",
                    "vehicle_number",
                    "year_make_model"
                  ],
                  "properties": {
                    "vin": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle."
                    },
                    "coverages": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "limit",
                          "deductible",
                          "coverage_type"
                        ],
                        "properties": {
                          "limit": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident')."
                          },
                          "deductible": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "description": "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies."
                          },
                          "coverage_type": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc."
                          }
                        },
                        "additionalProperties": false
                      },
                      "description": "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle."
                    },
                    "vehicle_number": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar."
                    },
                    "year_make_model": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The year, make, and model of the insured vehicle. May include body style or trim details."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle."
              },
              "coverages": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "coverage_name",
                    "coverage_limit",
                    "premium_by_vehicle"
                  ],
                  "properties": {
                    "coverage_name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc."
                    },
                    "coverage_limit": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit."
                    },
                    "premium_by_vehicle": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles."
              },
              "discounts": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "discount_type",
                    "applies_to_vehicles"
                  ],
                  "properties": {
                    "discount_type": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc."
                    },
                    "applies_to_vehicles": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount."
              },
              "total_fees": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              },
              "named_drivers": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "driver_name",
                    "driver_status"
                  ],
                  "properties": {
                    "driver_name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The full name of the driver listed on the policy. May include first, middle, and last names."
                    },
                    "driver_status": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers."
              },
              "policy_number": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology."
              },
              "rating_information": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "garaging_zip",
                    "vehicle_usage",
                    "vehicle_number",
                    "current_annual_mileage",
                    "previous_annual_mileage",
                    "years_of_driving_experience"
                  ],
                  "properties": {
                    "garaging_zip": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The ZIP code where the vehicle is primarily garaged or kept."
                    },
                    "vehicle_usage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc."
                    },
                    "vehicle_number": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The reference number or identifier for the vehicle as listed in the rating section."
                    },
                    "current_annual_mileage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The current estimated annual mileage for the vehicle."
                    },
                    "previous_annual_mileage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The previous year's annual mileage for the vehicle, if available."
                    },
                    "years_of_driving_experience": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The range or number of years of driving experience considered for rating this vehicle."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle."
              },
              "total_policy_premium": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              },
              "policy_effective_date": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar.",
                "extend:type": "date"
              },
              "insurance_company_name": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage."
              },
              "policy_expiration_date": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar.",
                "extend:type": "date"
              },
              "total_policy_premium_and_fees": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              }
            },
            "additionalProperties": false
          },
          "baseProcessor": "extraction_performance",
          "advancedOptions": {
            "reviewAgent": {
              "enabled": true
            },
            "advancedMultimodalEnabled": true
          }
        }
      }
    }
  ]
}
# Auto Insurance Declaration Page Processing — Extend AI Skill

## What this pipeline does

This pipeline extracts all critical policy details from an auto insurance declaration page—policy number, effective/expiration dates, insured vehicles (with VINs and year/make/model), coverage types with limits and deductibles per vehicle, named drivers, discounts, rating factors, and total premiums/fees. It uses agentic OCR parsing followed by structured extraction with a Zod schema to deliver a fully typed JSON object ready for downstream systems (policy management, underwriting, compliance audits).

## When to use this

- **Policy onboarding / intake**: Automatically capture all key fields when a customer uploads a declaration page into your portal.
- **Compliance & fraud detection**: Extract VINs, driver names, and coverage limits to cross-check against claims or third-party databases.
- **Premium audits**: Pull total premiums, discounts applied, and rating info to reconcile billing or detect pricing errors.
- **Multi-policy management**: Process declaration pages in batch to populate a policy database or data lake.
- **Proof of insurance verification**: Quickly validate policy number, effective date, and covered vehicles for roadside or claims scenarios.

## Processor pipeline

### Step 1: Parse (agentic_ocr mode)
**Processor:** `parse`  
**Purpose:** Convert the declaration page (often scanned, sometimes handwritten notes) into clean markdown with document-level chunking.  
**Key config:**
- `blockOptions.text.agentic.enabled: true` — enables agentic OCR, essential for handling printed forms, tables, and variable layouts.
- `chunkingStrategy.type: "document"` — treats the entire page as one chunk rather than splitting by semantic boundaries, preserving table structure and multi-column layouts common in insurance docs.

**Why this config:** Declaration pages are dense, structured tables. Agentic OCR accurately reads printed forms and scanned documents. Document-level chunking keeps the full context (all vehicles, coverages, drivers on one page) in one output, preventing fragmentation.

### Step 2: Extract (structured JSON with Zod schema)
**Processor:** `extract`  
**Purpose:** Pull 12 required fields (policy number, dates, vehicles array, coverages array, drivers array, discounts, rating info, premiums, fees) into a type-safe JSON object.  
**Key config:**
- `baseProcessor: "extraction_performance"` — optimized for accuracy on complex, multi-field forms (vs. `extraction_light` which trades quality for speed).
- `advancedOptions.reviewAgent.enabled: true` — runs a secondary review pass to catch missed or ambiguous fields, especially useful for handwritten or poor-quality scans.
- `advancedOptions.advancedMultimodalEnabled: true` — considers visual layout and OCR confidence when extracting nested arrays (vehicles, coverages) and matching vehicle #s across sections.

**Why this config:** Declaration pages are high-stakes. A missed VIN or wrong coverage limit causes downstream issues. Review agent + multimodal extraction significantly reduces hallucinations and omissions on dense, tabular docs.

## TypeScript implementation



## CLI equivalent

```bash
# Step 1: Parse with agentic OCR and document-level chunking
extend parse \
  declaration.pdf \
  --engine parse_performance \
  --block-options '{"text":{"agentic":{"enabled":true}}}' \
  --chunking-strategy document

# Step 2: Extract structured fields using the schema
extend extract \
  declaration.pdf \
  --schema auto-insurance-schema.json \
  --base-processor extraction_performance \
  --review-agent enabled \
  --advanced-multimodal enabled
```

**auto-insurance-schema.json:** (save this file)
```json
{
  "type": "object",
  "properties": {
    "policy_number": {
      "type": ["string", "null"],
      "description": "The unique identifier assigned to this auto insurance policy."
    },
    "insurance_company_name": {
      "type": ["string", "null"],
      "description": "The name of the insurance company providing this policy."
    },
    "policy_effective_date": {
      "type": ["string", "null"],
      "description": "The date when coverage begins (ISO yyyy-mm-dd).",
      "extend:type": "date"
    },
    "policy_expiration_date": {
      "type": ["string", "null"],
      "description": "The date when coverage ends (ISO yyyy-mm-dd).",
      "extend:type": "date"
    },
    "vehicles": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "vehicle_number": {"type": ["string", "null"]},
          "year_make_model": {"type": ["string", "null"]},
          "vin": {"type": ["string", "null"]},
          "coverages": {
import { ExtendClient, extendDate, extendCurrency } from "extend-ai";
import { z } from "zod";
import fs from "fs";

const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });

// Define Zod schema matching the auto insurance declaration page structure
const autoInsuranceSchema = z.object({
  policy_number: z.string().nullable().describe(
    "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology."
  ),
  insurance_company_name: z.string().nullable().describe(
    "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage."
  ),
  policy_effective_date: extendDate().describe(
    "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar."
  ),
  policy_expiration_date: extendDate().describe(
    "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar."
  ),
  
  vehicles: z.array(z.object({
    vehicle_number: z.string().nullable().describe(
      "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar."
    ),
    year_make_model: z.string().nullable().describe(
      "The year, make, and model of the insured vehicle. May include body style or trim details."
    ),
    vin: z.string().nullable().describe(
      "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle."
    ),
    coverages: z.array(z.object({
      coverage_type: z.string().nullable().describe(
        "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc."
      ),
      limit: z.string().nullable().describe(
        "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident')."
      ),
      deductible: z.number().nullable().describe(
        "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies."
      ),
    })).describe(
      "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle."
    ),
  })).describe(
    "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle."
  ),

  coverages: z.array(z.object({
    coverage_name: z.string().nullable().describe(
      "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc."
    ),
    coverage_limit: z.string().nullable().describe(
      "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit."
    ),
    premium_by_vehicle: z.string().nullable().describe(
      "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included."
    ),
  })).describe(
    "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles."
  ),

  named_drivers: z.array(z.object({
    driver_name: z.string().nullable().describe(
      "The full name of the driver listed on the policy. May include first, middle, and last names."
    ),
    driver_status: z.string().nullable().describe(
      "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations."
    ),
  })).describe(
    "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers."
  ),

  discounts: z.array(z.object({
    discount_type: z.string().nullable().describe(
      "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc."
    ),
    applies_to_vehicles: z.string().nullable().describe(
      "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'."
    ),
  })).describe(
    "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount."
  ),

  rating_information: z.array(z.object({
    vehicle_number: z.string().nullable().describe(
      "The reference number or identifier for the vehicle as listed in the rating section."
    ),
    garaging_zip: z.string().nullable().describe(
      "The ZIP code where the vehicle is primarily garaged or kept."
    ),
    vehicle_usage: z.string().nullable().describe(
      "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc."
    ),
    current_annual_mileage: z.string().nullable().describe(
      "The current estimated annual mileage for the vehicle."
    ),
    previous_annual_mileage: z.string().nullable().describe(
      "The previous year's annual mileage for the vehicle, if available."
    ),
    years_of_driving_experience: z.string().nullable().describe(
      "The range or number of years of driving experience considered for rating this vehicle."
    ),
  })).describe(
    "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle."
  ),

  total_policy_premium: extendCurrency().describe(
    "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar."
  ),

  total_fees: extendCurrency().describe(
    "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar."
  ),

  total_policy_premium_and_fees: extendCurrency().describe(
    "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar."
  ),
});

type AutoInsuranceDeclaration = z.infer<typeof autoInsuranceSchema>;

export async function processAutoInsuranceDeclarationPage(
  filePath: string
): Promise<AutoInsuranceDeclaration> {
  try {
    // Convert local file to data URL (base64)
    const fileBuffer = fs.readFileSync(filePath);
    const base64 = fileBuffer.toString("base64");
    const dataUrl = `data:application/octet-stream;base64,${base64}`;

    console.log(`Processing auto insurance declaration page: ${filePath}`);

    // Step 1: Parse with agentic OCR
    console.log("Step 1: Parsing document with agentic OCR...");
    const parseRun = await client.parseRuns.createAndPoll({
      file: { url: dataUrl },
      config: {
        blockOptions: {
          text: {
            agentic: {
              enabled: true,
            },
          },
        },
        chunkingStrategy: {
          type: "document",
        },
      },
    });

    if (parseRun.status !== "PROCESSED") {
      throw new Error(`Parse failed with status: ${parseRun.status}`);
    }

    console.log(
      `Parsing complete. Extracted ${parseRun.output.chunks.length} chunk(s).`
    );

    // Step 2: Extract structured fields with Zod schema
    console.log("Step 2: Extracting structured fields...");
    const extractRun = await client.extractRuns.createAndPoll({
      file: { url: dataUrl },
      config: {
        schema: autoInsuranceSchema,
        baseProcessor: "extraction_performance",
        advancedOptions: {
          reviewAgent: {
            enabled: true,
          },
          advancedMultimodalEnabled: true,
        },
      },
    });

    if (extractRun.status !== "PROCESSED") {
      throw new Error(`Extraction failed with status: ${extractRun.status}`);
    }

    const result = extractRun.output.value as AutoInsuranceDeclaration;

    // Log summary
    console.log("\n=== Extraction Summary ===");
    console.log(`Policy Number: ${result.policy_number}`);
    console.log(`Insurance Company: ${result.insurance_company_name}`);
    console.log(`Effective Date: ${result.policy_effective_date}`);
    console.log(`Expiration Date: ${result.policy_expiration_date}`);
    console.log(`Vehicles Found: ${result.vehicles?.length ?? 0}`);
    console.log(`Named Drivers: ${result.named_drivers?.length ?? 0}`);
    console.log(`Discounts Applied: ${result.discounts?.length ?? 0}`);
    console.log(
      `Total Premium: ${result.total_policy_premium?.amount} ${result.total_policy_premium?.iso_4217_currency_code}`
    );
    console.log(
      `Total Fees: ${result.total_fees?.amount} ${result.total_fees?.iso_4217_currency_code}`
    );
    console.log(
      `Total Due: ${result.total_policy_premium_and_fees?.amount} ${result.total_policy_premium_and_fees?.iso_4217_currency_code}`
    );

    // Log vehicle details
    if (result.vehicles && result.vehicles.length > 0) {
      console.log("\n=== Vehicles ===");
      result.vehicles.forEach((vehicle, idx) => {
        console.log(
          `${vehicle.vehicle_number || `Vehicle ${idx + 1}`}: ${vehicle.year_make_model}`
        );
        console.log(`  VIN: ${vehicle.vin}`);
        console.log(`  Coverages: ${vehicle.coverages?.length ?? 0}`);
        vehicle.coverages?.forEach((cov) => {
          console.log(
            `    - ${cov.coverage_type}: Limit ${cov.limit}, Deductible $${cov.deductible}`
          );
        });
      });
    }

    return result;
  } catch (error) {
    console.error("Error processing auto insurance declaration page:", error);
    throw error;
  }
}

// Example invocation for testing
const filePath = process.argv[2] || "./sample-declaration.pdf";
processAutoInsuranceDeclarationPage(filePath)
  .then((result) => {
    console.log("\n=== Full Extraction Output ===");
    console.log(JSON.stringify(result, null, 2));
  })
  .catch((err) => {
    console.error("Fatal error:", err.message);
    process.exit(1);
  });
import os
import json
from typing import Optional
from dataclasses import dataclass
from extend_ai import Extend

client = Extend(token=os.environ["EXTEND_API_KEY"])

# Define extraction schema matching the auto insurance declaration page structure
auto_insurance_schema = {
    "type": "object",
    "properties": {
        "policy_number": {
            "type": ["string", "null"],
            "description": "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology."
        },
        "insurance_company_name": {
            "type": ["string", "null"],
            "description": "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage."
        },
        "policy_effective_date": {
            "type": ["string", "null"],
            "extend:type": "date",
            "description": "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar."
        },
        "policy_expiration_date": {
            "type": ["string", "null"],
            "extend:type": "date",
            "description": "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar."
        },
        "vehicles": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "vehicle_number": {
                        "type": ["string", "null"],
                        "description": "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar."
                    },
                    "year_make_model": {
                        "type": ["string", "null"],
                        "description": "The year, make, and model of the insured vehicle. May include body style or trim details."
                    },
                    "vin": {
                        "type": ["string", "null"],
                        "description": "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle."
                    },
                    "coverages": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "coverage_type": {
                                    "type": ["string", "null"],
                                    "description": "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc."
                                },
                                "limit": {
                                    "type": ["string", "null"],
                                    "description": "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident')."
                                },
                                "deductible": {
                                    "type": ["number", "null"],
                                    "description": "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies."
                                }
                            },
                            "required": ["coverage_type", "limit", "deductible"]
                        },
                        "description": "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle."
                    }
                },
                "required": ["vehicle_number", "year_make_model", "vin", "coverages"]
            },
            "description": "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle."
        },
        "coverages": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "coverage_name": {
                        "type": ["string", "null"],
                        "description": "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc."
                    },
                    "coverage_limit": {
                        "type": ["string", "null"],
                        "description": "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit."
                    },
                    "premium_by_vehicle": {
                        "type": ["string", "null"],
                        "description": "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included."
                    }
                },
                "required": ["coverage_name", "coverage_limit", "premium_by_vehicle"]
            },
            "description": "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles."
        },
        "named_drivers": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "driver_name": {
                        "type": ["string", "null"],
                        "description": "The full name of the driver listed on the policy. May include first, middle, and last names."
                    },
                    "driver_status": {
                        "type": ["string", "null"],
                        "description": "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations."
                    }
                },
                "required": ["driver_name", "driver_status"]
            },
            "description": "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers."
        },
        "discounts": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "discount_type": {
                        "type": ["string", "null"],
                        "description": "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc."
                    },
                    "applies_to_vehicles": {
                        "type": ["string", "null"],
                        "description": "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'."
                    }
                },
                "required": ["discount_type", "applies_to_vehicles"]
            },
            "description": "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount."
        },
        "rating_information": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "vehicle_number": {
                        "type": ["string", "null"],
                        "description": "The reference number or identifier for the vehicle as listed in the rating section."
                    },
                    "garaging_zip": {
                        "type": ["string", "null"],
                        "description": "The ZIP code where the vehicle is primarily garaged or kept."
                    },
                    "vehicle_usage": {
                        "type": ["string", "null"],
                        "description": "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc."
                    },
                    "current_annual_mileage": {
                        "type": ["string", "null"],
                        "description": "The current estimated annual mileage for the vehicle."
                    },
                    "previous_annual_mileage": {
                        "type": ["string", "null"],
                        "description": "The previous year's annual mileage for the vehicle, if available."
                    },
                    "years_of_driving_experience": {
                        "type": ["string", "null"],
                        "description": "The range or number of years of driving experience considered for rating this vehicle."
                    }
                },
                "required": ["vehicle_number", "garaging_zip", "vehicle_usage", "current_annual_mileage", "previous_annual_mileage", "years_of_driving_experience"]
            },
            "description": "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle."
        },
        "total_policy_premium": {
            "type": "object",
            "properties": {
                "amount": {
                    "type": ["number", "null"]
                },
                "iso_4217_currency_code": {
                    "type": ["string", "null"]
                }
            },
            "required": ["amount", "iso_4217_currency_code"],
            "extend:type": "currency",
            "description": "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar."
        },
        "total_fees": {
            "type": "object",
            "properties": {
                "amount": {
                    "type": ["number", "null"]
                },
                "iso_4217_currency_code": {
                    "type": ["string", "null"]
                }
            },
            "required": ["amount", "iso_4217_currency_code"],
            "extend:type": "currency",
            "description": "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar."
        },
        "total_policy_premium_and_fees": {
            "type": "object",
            "properties": {
                "amount": {
                    "type": ["number", "null"]
                },
                "iso_4217_currency_code": {
                    "type": ["string", "null"]
                }
            },
            "required": ["amount", "iso_4217_currency_code"],
            "extend:type": "currency",
            "description": "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar."
        }
    },
    "required": ["policy_number", "insurance_company_name", "policy_effective_date", "policy_expiration_date", "vehicles", "coverages", "named_drivers", "discounts", "rating_information", "total_policy_premium", "total_fees", "total_policy_premium_and_fees"]
}


async def process_auto_insurance_declaration_page(file_path: str) -> dict:
    """
    Process an auto insurance declaration page and extract structured data.
    
    Args:
        file_path: Path to the insurance declaration file
        
    Returns:
        Extracted auto insurance data as a dictionary
    """
    try:
        print(f"Processing auto insurance declaration page: {file_path}")
        
        # Step 1: Parse with agentic OCR
        print("Step 1: Parsing document with agentic OCR...")
        parse_run = await client.parse_runs.create_and_poll(
            file={"path": file_path},
            config={
                "block_options": {
                    "text": {
                        "agentic": {
                            "enabled": True
                        }
                    }
                },
                "chunking_strategy": {
                    "type": "document"
                }
            }
        )
        
        if parse_run.status != "PROCESSED":
            raise Exception(f"Parse failed with status: {parse_run.status}")
        
        print(f"Parsing complete. Extracted {len(parse_run.output['chunks'])} chunk(s).")
        
        # Step 2: Extract structured fields with schema
        print("Step 2: Extracting structured fields...")
        extract_run = await client.extract_runs.create_and_poll(
            file={"path": file_path},
            config={
                "schema": auto_insurance_schema,
                "base_processor": "extraction_performance",
                "advanced_options": {
                    "review_agent": {
                        "enabled": True
                    },
                    "advanced_multimodal_enabled": True
                }
            }
        )
        
        if extract_run.status != "PROCESSED":
            raise Exception(f"Extraction failed with status: {extract_run.status}")
        
        result = extract_run.output["value"]
        
        # Log summary
        print("\n=== Extraction Summary ===")
        print(f"Policy Number: {result.get('policy_number')}")
        print(f"Insurance Company: {result.get('insurance_company_name')}")
        print(f"Effective Date: {result.get('policy_effective_date')}")
        print(f"Expiration Date: {result.get('policy_expiration_date')}")
        print(f"Vehicles Found: {len(result.get('vehicles', []))}")
        print(f"Named Drivers: {len(result.get('named_drivers', []))}")
        print(f"Discounts Applied: {len(result.get('discounts', []))}")
        
        total_premium = result.get('total_policy_premium', {})
        print(f"Total Premium: {total_premium.get('amount')} {total_premium.get('iso_4217_currency_code')}")
        
        total_fees = result.get('total_fees', {})
        print(f"Total Fees: {total_fees.get('amount')} {total_fees.get('iso_4217_currency_code')}")
        
        total_due = result.get('total_policy_premium_and_fees', {})
        print(f"Total Due: {total_due.get('amount')} {total_due.get('iso_4217_currency_code')}")
        
        # Log vehicle details
        if result.get('vehicles'):
            print("\n=== Vehicles ===")
            for idx, vehicle in enumerate(result['vehicles']):
                vehicle_label = vehicle.get('vehicle_number') or f"Vehicle {idx + 1}"
                print(f"{vehicle_label}: {vehicle.get('year_make_model')}")
                print(f"  VIN: {vehicle.get('vin')}")
                print(f"  Coverages: {len(vehicle.get('coverages', []))}")
                for cov in vehicle.get('coverages', []):
                    print(f"    - {cov.get('coverage_type')}: Limit {cov.get('limit')}, Deductible ${cov.get('deductible')}")
        
        return result
        
    except Exception as error:
        print(f"Error processing auto insurance declaration page: {error}")
        raise


if __name__ == "__main__":
    import sys
    import asyncio
    
    file_path = sys.argv[1] if len(sys.argv) > 1 else "./sample-declaration.pdf"
    
    async def main():
        try:
            result = await process_auto_insurance_declaration_page(file_path)
            print("\n=== Full Extraction Output ===")
            print(json.dumps(result, indent=2))
        except Exception as err:
            print(f"Fatal error: {err}")
            sys.exit(1)
    
    asyncio.run(main())
// This code uses the Extend REST API directly via java.net.http.HttpClient
// because Extend does not publish an official Java SDK yet.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AutoInsuranceDeclarationProcessor {

    private static final String EXTEND_API_BASE = "https://api.extend.ai";
    private static final String API_KEY = System.getenv("EXTEND_API_KEY");
    private final HttpClient httpClient = HttpClient.newHttpClient();

    public static class CurrencyValue {
        public Double amount;
        public String iso_4217_currency_code;

        public CurrencyValue(Double amount, String iso_4217_currency_code) {
            this.amount = amount;
            this.iso_4217_currency_code = iso_4217_currency_code;
        }
    }

    public static class Coverage {
        public String coverage_type;
        public String limit;
        public Double deductible;
    }

    public static class Vehicle {
        public String vehicle_number;
        public String year_make_model;
        public String vin;
        public List<Coverage> coverages;
    }

    public static class PolicyCoverage {
        public String coverage_name;
        public String coverage_limit;
        public String premium_by_vehicle;
    }

    public static class NamedDriver {
        public String driver_name;
        public String driver_status;
    }

    public static class Discount {
        public String discount_type;
        public String applies_to_vehicles;
    }

    public static class RatingInfo {
        public String vehicle_number;
        public String garaging_zip;
        public String vehicle_usage;
        public String current_annual_mileage;
        public String previous_annual_mileage;
        public String years_of_driving_experience;
    }

    public static class AutoInsuranceDeclaration {
        public String policy_number;
        public String insurance_company_name;
        public String policy_effective_date;
        public String policy_expiration_date;
        public List<Vehicle> vehicles;
        public List<PolicyCoverage> coverages;
        public List<NamedDriver> named_drivers;
        public List<Discount> discounts;
        public List<RatingInfo> rating_information;
        public CurrencyValue total_policy_premium;
        public CurrencyValue total_fees;
        public CurrencyValue total_policy_premium_and_fees;
    }

    private String fileToDataUrl(String filePath) throws IOException {
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
        String base64 = Base64.getEncoder().encodeToString(fileBytes);
        return "data:application/octet-stream;base64," + base64;
    }

    private String buildSchemaJson() {
        return """
            {
              "type": "object",
              "properties": {
                "policy_number": {"type": ["string", "null"]},
                "insurance_company_name": {"type": ["string", "null"]},
                "policy_effective_date": {"type": ["string", "null"], "extend:type": "date"},
                "policy_expiration_date": {"type": ["string", "null"], "extend:type": "date"},
                "vehicles": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "vehicle_number": {"type": ["string", "null"]},
                      "year_make_model": {"type": ["string", "null"]},
                      "vin": {"type": ["string", "null"]},
                      "coverages": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "coverage_type": {"type": ["string", "null"]},
                            "limit": {"type": ["string", "null"]},
                            "deductible": {"type": ["number", "null"]}
                          }
                        }
                      }
                    }
                  }
                },
                "coverages": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "coverage_name": {"type": ["string", "null"]},
                      "coverage_limit": {"type": ["string", "null"]},
                      "premium_by_vehicle": {"type": ["string", "null"]}
                    }
                  }
                },
                "named_drivers": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "driver_name": {"type": ["string", "null"]},
                      "driver_status": {"type": ["string", "null"]}
                    }
                  }
                },
                "discounts": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "discount_type": {"type": ["string", "null"]},
                      "applies_to_vehicles": {"type": ["string", "null"]}
                    }
                  }
                },
                "rating_information": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "vehicle_number": {"type": ["string", "null"]},
                      "garaging_zip": {"type": ["string", "null"]},
                      "vehicle_usage": {"type": ["string", "null"]},
                      "current_annual_mileage": {"type": ["string", "null"]},
                      "previous_annual_mileage": {"type": ["string", "null"]},
                      "years_of_driving_experience": {"type": ["string", "null"]}
                    }
                  }
                },
                "total_policy_premium": {
                  "type": "object",
                  "properties": {
                    "amount": {"type": ["number", "null"]},
                    "iso_4217_currency_code": {"type": ["string", "null"]}
                  },
                  "extend:type": "currency"
                },
                "total_fees": {
                  "type": "object",
                  "properties": {
                    "amount": {"type": ["number", "null"]},
                    "iso_4217_currency_code": {"type": ["string", "null"]}
                  },
                  "extend:type": "currency"
                },
                "total_policy_premium_and_fees": {
                  "type": "object",
                  "properties": {
                    "amount": {"type": ["number", "null"]},
                    "iso_4217_currency_code": {"type": ["string", "null"]}
                  },
                  "extend:type": "currency"
                }
              }
            }
            """;
    }

    private String makeRequest(String endpoint, String jsonBody) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(java.net.URI.create(EXTEND_API_BASE + endpoint))
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IOException("API request failed with status " + response.statusCode() + ": " + response.body());
        }
        return response.body();
    }

    private String pollRunStatus(String runId, String endpoint) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();
        long timeout = 300000; // 5 minutes

        while (System.currentTimeMillis() - startTime < timeout) {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(java.net.URI.create(EXTEND_API_BASE + endpoint + "/" + runId))
                    .header("Authorization", "Bearer " + API_KEY)
                    .GET()
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() != 200) {
                throw new IOException("Failed to poll status: " + response.statusCode());
            }

            // Simple JSON parsing to check status
            if (response.body().contains("\"status\":\"PROCESSED\"")) {
                return response.body();
            }
            if (response.body().contains("\"status\":\"FAILED\"")) {
                throw new IOException("Run failed: " + response.body());
            }

            Thread.sleep(2000); // Wait 2 seconds before retry
        }
        throw new IOException("Run polling timeout");
    }

    public AutoInsuranceDeclaration processAutoInsuranceDeclarationPage(String filePath)
            throws IOException, InterruptedException {
        try {
            // Convert local file to data URL (base64)
            String dataUrl = fileToDataUrl(filePath);
            System.out.println("Processing auto insurance declaration page: " + filePath);

            // Step 1: Parse with agentic OCR
            System.out.println("Step 1: Parsing document with agentic OCR...");
            String parseRequestBody = String.format(
                    """
                    {
                      "file": {"url": "%s"},
                      "config": {
                        "blockOptions": {
                          "text": {
                            "agentic": {
                              "enabled": true
                            }
                          }
                        },
                        "chunkingStrategy": {
                          "type": "document"
                        }
                      }
                    }
                    """, dataUrl.replace("\"", "\\\""));

            String parseResponse = makeRequest("/v1/parse_runs", parseRequestBody);
            // Extract runId from response
            String parseRunId = extractJsonField(parseResponse, "id");
            String parseResult = pollRunStatus(parseRunId, "/v1/parse_runs");

            if (!parseResult.contains("\"status\":\"PROCESSED\"")) {
                throw new IOException("Parse failed");
            }
            System.out.println("Parsing complete.");

            // Step 2: Extract structured fields
            System.out.println("Step 2: Extracting structured fields...");
            String extractRequestBody = String.format(
                    """
                    {
                      "file": {"url": "%s"},
                      "config": {
                        "schema": %s,
                        "baseProcessor": "extraction_performance",
                        "advancedOptions": {
                          "reviewAgent": {
                            "enabled": true
                          },
                          "advancedMultimodalEnabled": true
                        }
                      }
                    }
                    """, dataUrl.replace("\"", "\\\""), buildSchemaJson());

            String extractResponse = makeRequest("/v1/extract_runs", extractRequestBody);
            String extractRunId = extractJsonField(extractResponse, "id");
            String extractResult = pollRunStatus(extractRunId, "/v1/extract_runs");

            if (!extractResult.contains("\"status\":\"PROCESSED\"")) {
                throw new IOException("Extraction failed");
            }

            // Parse result into AutoInsuranceDeclaration
            AutoInsuranceDeclaration result = parseExtractResult(extractResult);

            // Log summary
            System.out.println("\n=== Extraction Summary ===");
            System.out.println("Policy Number: " + result.policy_number);
            System.out.println("Insurance Company: " + result.insurance_company_name);
            System.out.println("Effective Date: " + result.policy_effective_date);
            System.out.println("Expiration Date: " + result.policy_expiration_date);
            System.out.println("Vehicles Found: " + (result.vehicles != null ? result.vehicles.size() : 0));
            System.out.println("Named Drivers: " + (result.named_drivers != null ? result.named_drivers.size() : 0));
            System.out.println("Discounts Applied: " + (result.discounts != null ? result.discounts.size() : 0));
            if (result.total_policy_premium != null) {
                System.out.println("Total Premium: " + result.total_policy_premium.amount + " " + result.total_policy_premium.iso_4217_currency_code);
            }
            if (result.total_fees != null) {
                System.out.println("Total Fees: " + result.total_fees.amount + " " + result.total_fees.iso_4217_currency_code);
            }
            if (result.total_policy_premium_and_fees != null) {
                System.out.println("Total Due: " + result.total_policy_premium_and_fees.amount + " " + result.total_policy_premium_and_fees.iso_4217_currency_code);
            }

            // Log vehicle details
            if (result.vehicles != null && !result.vehicles.isEmpty()) {
                System.out.println("\n=== Vehicles ===");
                for (int i = 0; i < result.vehicles.size(); i++) {
                    Vehicle vehicle = result.vehicles.get(i);
                    String vehicleLabel = vehicle.vehicle_number != null ? vehicle.vehicle_number : "Vehicle " + (i + 1);
                    System.out.println(vehicleLabel + ": " + vehicle.year_make_model);
                    System.out.println("  VIN: " + vehicle.vin);
                    System.out.println("  Coverages: " + (vehicle.coverages != null ? vehicle.coverages.size() : 0));
                    if (vehicle.coverages != null) {
                        for (Coverage cov : vehicle.coverages) {
                            System.out.println("    - " + cov.coverage_type + ": Limit " + cov.limit + ", Deductible $" + cov.deductible);
                        }
                    }
                }
            }

            return result;
        } catch (Exception error) {
            System.err.println("Error processing auto insurance declaration page: " + error.getMessage());
            throw error;
        }
    }

    private String extractJsonField(String json, String fieldName) {
        String pattern = "\"" + fieldName + "\":\"([^\"]*)\"";
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
        java.util.regex.Matcher m = p.matcher(json);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    private AutoInsuranceDeclaration parseExtractResult(String json) {
        AutoInsuranceDeclaration result = new AutoInsuranceDeclaration();
        // Simple JSON extraction (for production, use a proper JSON library)
        result.policy_number = extractJsonField(json, "policy_number");
        result.insurance_company_name = extractJsonField(json, "insurance_company_name");
        result.policy_effective_date = extractJsonField(json, "policy_effective_date");
        result.policy_expiration_date = extractJsonField(json, "policy_expiration_date");
        result.vehicles = new ArrayList<>();
        result.coverages = new ArrayList<>();
        result.named_drivers = new ArrayList<>();
        result.discounts = new ArrayList<>();
        result.rating_information = new ArrayList<>();
        return result;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        String filePath = args.length > 0 ? args[0] : "./sample-declaration.pdf";
        AutoInsuranceDeclarationProcessor processor = new AutoInsuranceDeclarationProcessor();

        try {
            AutoInsuranceDeclaration result = processor.processAutoInsuranceDeclarationPage(filePath);
            System.out.println("\n=== Extraction completed successfully ===");
        } catch (Exception err) {
            System.err.println("Fatal error: " + err.getMessage());
            System.exit(1);
        }
    }
}
// This example uses the Extend REST API directly because Extend has no official Go SDK.
// It calls https://api.extend.ai endpoints with standard net/http and encoding/json.

package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

// Currency represents a monetary value with currency code
type Currency struct {
	Amount              *float64 `json:"amount"`
	ISO4217CurrencyCode *string  `json:"iso_4217_currency_code"`
}

// Coverage represents a single coverage for a vehicle
type Coverage struct {
	CoverageType *string  `json:"coverage_type"`
	Limit        *string  `json:"limit"`
	Deductible   *float64 `json:"deductible"`
}

// Vehicle represents an insured vehicle
type Vehicle struct {
	VehicleNumber  *string     `json:"vehicle_number"`
	YearMakeModel  *string     `json:"year_make_model"`
	VIN            *string     `json:"vin"`
	Coverages      []Coverage  `json:"coverages"`
}

// PolicyCoverage represents a policy-level coverage
type PolicyCoverage struct {
	CoverageName    *string `json:"coverage_name"`
	CoverageLimit   *string `json:"coverage_limit"`
	PremiumByVehicle *string `json:"premium_by_vehicle"`
}

// Discount represents an applied discount
type Discount struct {
	DiscountType     *string `json:"discount_type"`
	AppliesToVehicles *string `json:"applies_to_vehicles"`
}

// NamedDriver represents a driver on the policy
type NamedDriver struct {
	DriverName   *string `json:"driver_name"`
	DriverStatus *string `json:"driver_status"`
}

// RatingInfo represents rating details for a vehicle
type RatingInfo struct {
	VehicleNumber          *string `json:"vehicle_number"`
	GaragingZip            *string `json:"garaging_zip"`
	VehicleUsage           *string `json:"vehicle_usage"`
	CurrentAnnualMileage   *string `json:"current_annual_mileage"`
	PreviousAnnualMileage  *string `json:"previous_annual_mileage"`
	YearsOfDrivingExperience *string `json:"years_of_driving_experience"`
}

// AutoInsuranceDeclaration represents the full extracted declaration page
type AutoInsuranceDeclaration struct {
	PolicyNumber              *string             `json:"policy_number"`
	InsuranceCompanyName      *string             `json:"insurance_company_name"`
	PolicyEffectiveDate       *string             `json:"policy_effective_date"`
	PolicyExpirationDate      *string             `json:"policy_expiration_date"`
	Vehicles                  []Vehicle           `json:"vehicles"`
	Coverages                 []PolicyCoverage    `json:"coverages"`
	NamedDrivers              []NamedDriver       `json:"named_drivers"`
	Discounts                 []Discount          `json:"discounts"`
	RatingInformation         []RatingInfo        `json:"rating_information"`
	TotalPolicyPremium        *Currency           `json:"total_policy_premium"`
	TotalFees                 *Currency           `json:"total_fees"`
	TotalPolicyPremiumAndFees *Currency           `json:"total_policy_premium_and_fees"`
}

// parseRunResponse is the response from the parse endpoint
type parseRunResponse struct {
	Status string `json:"status"`
	Output struct {
		Chunks []interface{} `json:"chunks"`
	} `json:"output"`
	ID string `json:"id"`
}

// extractRunResponse is the response from the extract endpoint
type extractRunResponse struct {
	Status string `json:"status"`
	Output struct {
		Value AutoInsuranceDeclaration `json:"value"`
	} `json:"output"`
	ID string `json:"id"`
}

func processAutoInsuranceDeclarationPage(filePath string, apiKey string) (*AutoInsuranceDeclaration, error) {
	// Read file and convert to base64
	fileBuffer, err := os.ReadFile(filePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	base64Data := base64.StdEncoding.EncodeToString(fileBuffer)
	dataURL := "data:application/octet-stream;base64," + base64Data

	fmt.Printf("Processing auto insurance declaration page: %s\n", filePath)

	// Step 1: Parse with agentic OCR
	fmt.Println("Step 1: Parsing document with agentic OCR...")

	parseConfig := map[string]interface{}{
		"file": map[string]string{
			"url": dataURL,
		},
		"config": map[string]interface{}{
			"blockOptions": map[string]interface{}{
				"text": map[string]interface{}{
					"agentic": map[string]bool{
						"enabled": true,
					},
				},
			},
			"chunkingStrategy": map[string]string{
				"type": "document",
			},
		},
	}

	parseBody, err := json.Marshal(parseConfig)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal parse config: %w", err)
	}

	parseID, err := createParseRun(apiKey, parseBody)
	if err != nil {
		return nil, fmt.Errorf("failed to create parse run: %w", err)
	}

	parseResult, err := pollParseRun(apiKey, parseID)
	if err != nil {
		return nil, fmt.Errorf("failed to poll parse run: %w", err)
	}

	if parseResult.Status != "PROCESSED" {
		return nil, fmt.Errorf("parse failed with status: %s", parseResult.Status)
	}

	fmt.Printf("Parsing complete. Extracted %d chunk(s).\n", len(parseResult.Output.Chunks))

	// Step 2: Extract structured fields
	fmt.Println("Step 2: Extracting structured fields...")

	extractSchema := map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"policy_number": map[string]interface{}{
				"type": []string{"string", "null"},
			},
			"insurance_company_name": map[string]interface{}{
				"type": []string{"string", "null"},
			},
			"policy_effective_date": map[string]interface{}{
				"type":       []string{"string", "null"},
				"extend:type": "date",
			},
			"policy_expiration_date": map[string]interface{}{
				"type":       []string{"string", "null"},
				"extend:type": "date",
			},
			"vehicles": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"properties": map[string]interface{}{
						"vehicle_number": map[string]interface{}{"type": []string{"string", "null"}},
						"year_make_model": map[string]interface{}{"type": []string{"string", "null"}},
						"vin": map[string]interface{}{"type": []string{"string", "null"}},
						"coverages": map[string]interface{}{
							"type": "array",
							"items": map[string]interface{}{
								"type": "object",
								"properties": map[string]interface{}{
									"coverage_type": map[string]interface{}{"type": []string{"string", "null"}},
									"limit":         map[string]interface{}{"type": []string{"string", "null"}},
									"deductible":    map[string]interface{}{"type": []string{"number", "null"}},
								},
							},
						},
					},
				},
			},
			"coverages": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"properties": map[string]interface{}{
						"coverage_name":    map[string]interface{}{"type": []string{"string", "null"}},
						"coverage_limit":   map[string]interface{}{"type": []string{"string", "null"}},
						"premium_by_vehicle": map[string]interface{}{"type": []string{"string", "null"}},
					},
				},
			},
			"named_drivers": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"properties": map[string]interface{}{
						"driver_name":   map[string]interface{}{"type": []string{"string", "null"}},
						"driver_status": map[string]interface{}{"type": []string{"string", "null"}},
					},
				},
			},
			"discounts": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"properties": map[string]interface{}{
						"discount_type":      map[string]interface{}{"type": []string{"string", "null"}},
						"applies_to_vehicles": map[string]interface{}{"type": []string{"string", "null"}},
					},
				},
			},
			"rating_information": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"properties": map[string]interface{}{
						"vehicle_number":           map[string]interface{}{"type": []string{"string", "null"}},
						"garaging_zip":             map[string]interface{}{"type": []string{"string", "null"}},
						"vehicle_usage":            map[string]interface{}{"type": []string{"string", "null"}},
						"current_annual_mileage":   map[string]interface{}{"type": []string{"string", "null"}},
						"previous_annual_mileage":  map[string]interface{}{"type": []string{"string", "null"}},
						"years_of_driving_experience": map[string]interface{}{"type": []string{"string", "null"}},
					},
				},
			},
			"total_policy_premium": map[string]interface{}{
				"type":        "object",
				"extend:type": "currency",
				"properties": map[string]interface{}{
					"amount":                  map[string]interface{}{"type": []string{"number", "null"}},
					"iso_4217_currency_code": map[string]interface{}{"type": []string{"string", "null"}},
				},
			},
			"total_fees": map[string]interface{}{
				"type":        "object",
				"extend:type": "currency",
				"properties": map[string]interface{}{
					"amount":                  map[string]interface{}{"type": []string{"number", "null"}},
					"iso_4217_currency_code": map[string]interface{}{"type": []string{"string", "null"}},
				},
			},
			"total_policy_premium_and_fees": map[string]interface{}{
				"type":        "object",
				"extend:type": "currency",
				"properties": map[string]interface{}{
					"amount":                  map[string]interface{}{"type": []string{"number", "null"}},
					"iso_4217_currency_code": map[string]interface{}{"type": []string{"string", "null"}},
				},
			},
		},
	}

	extractConfig := map[string]interface{}{
		"file": map[string]string{
			"url": dataURL,
		},
		"config": map[string]interface{}{
			"schema":        extractSchema,
			"baseProcessor": "extraction_performance",
			"advancedOptions": map[string]interface{}{
				"reviewAgent": map[string]bool{
					"enabled": true,
				},
				"advancedMultimodalEnabled": true,
			},
		},
	}

	extractBody, err := json.Marshal(extractConfig)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal extract config: %w", err)
	}

	extractID, err := createExtractRun(apiKey, extractBody)
	if err != nil {
		return nil, fmt.Errorf("failed to create extract run: %w", err)
	}

	extractResult, err := pollExtractRun(apiKey, extractID)
	if err != nil {
		return nil, fmt.Errorf("failed to poll extract run: %w", err)
	}

	if extractResult.Status != "PROCESSED" {
		return nil, fmt.Errorf("extraction failed with status: %s", extractResult.Status)
	}

	result := &extractResult.Output.Value

	// Log summary
	fmt.Println("\n=== Extraction Summary ===")
	fmt.Printf("Policy Number: %v\n", result.PolicyNumber)
	fmt.Printf("Insurance Company: %v\n", result.InsuranceCompanyName)
	fmt.Printf("Effective Date: %v\n", result.PolicyEffectiveDate)
	fmt.Printf("Expiration Date: %v\n", result.PolicyExpirationDate)
	fmt.Printf("Vehicles Found: %d\n", len(result.Vehicles))
	fmt.Printf("Named Drivers: %d\n", len(result.NamedDrivers))
	fmt.Printf("Discounts Applied: %d\n", len(result.Discounts))

	if result.TotalPolicyPremium != nil {
		fmt.Printf("Total Premium: %v %v\n", result.TotalPolicyPremium.Amount, result.TotalPolicyPremium.ISO4217CurrencyCode)
	}
	if result.TotalFees != nil {
		fmt.Printf("Total Fees: %v %v\n", result.TotalFees.Amount, result.TotalFees.ISO4217CurrencyCode)
	}
	if result.TotalPolicyPremiumAndFees != nil {
		fmt.Printf("Total Due: %v %v\n", result.TotalPolicyPremiumAndFees.Amount, result.TotalPolicyPremiumAndFees.ISO4217CurrencyCode)
	}

	// Log vehicle details
	if len(result.Vehicles) > 0 {
		fmt.Println("\n=== Vehicles ===")
		for idx, vehicle := range result.Vehicles {
			vehicleNum := "Vehicle " + fmt.Sprintf("%d", idx+1)
			if vehicle.VehicleNumber != nil {
				vehicleNum = *vehicle.VehicleNumber
			}
			yearMakeModel := ""
			if vehicle.YearMakeModel != nil {
				yearMakeModel = *vehicle.YearMakeModel
			}
			fmt.Printf("%s: %s\n", vehicleNum, yearMakeModel)

			if vehicle.VIN != nil {
				fmt.Printf("  VIN: %s\n", *vehicle.VIN)
			}
			fmt.Printf("  Coverages: %d\n", len(vehicle.Coverages))

			for _, cov := range vehicle.Coverages {
				covType := ""
				if cov.CoverageType != nil {
					covType = *cov.CoverageType
				}
				limit := ""
				if cov.Limit != nil {
					limit = *cov.Limit
				}
				ded := ""
				if cov.Deductible != nil {
					ded = fmt.Sprintf("%.0f", *cov.Deductible)
				}
				fmt.Printf("    - %s: Limit %s, Deductible $%s\n", covType, limit, ded)
			}
		}
	}

	return result, nil
}

func createParseRun(apiKey string, body []byte) (string, error) {
	req, err := http.NewRequest("POST", "https://api.extend.ai/parse_runs", bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result map[string]interface{}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", err
	}

	if id, ok := result["id"].(string); ok {
		return id, nil
	}
	return "", fmt.Errorf("no id in response")
}

func pollParseRun(apiKey string, runID string) (*parseRunResponse, error) {
	for {
		req, err := http.NewRequest("GET", "https://api.extend.ai/parse_runs/"+runID, nil)
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+apiKey)

		client := &http.Client{Timeout: 10 * time.Second}
		resp, err := client.Do(req)
		if err != nil {
			return nil, err
		}

		data, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			return nil, err
		}

		var result parseRunResponse
		if err := json.Unmarshal(data, &result); err != nil {
			return nil, err
		}

		if result.Status == "PROCESSED" || result.Status == "FAILED" {
			return &result, nil
		}

		time.Sleep(2 * time.Second)
	}
}

func createExtractRun(apiKey string, body []byte) (string, error) {
	req, err := http.NewRequest("POST", "https://api.extend.ai/extract_runs", bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result map[string]interface{}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", err
	}

	if id, ok := result["id"].(string); ok {
		return id, nil
	}
	return "", fmt.Errorf("no id in response")
}

func pollExtractRun(apiKey string, runID string) (*extractRunResponse, error) {
	for {
		req, err := http.NewRequest("GET", "https://api.extend.ai/extract_runs/"+runID, nil)
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+apiKey)

		client := &http.Client{Timeout: 10 * time.Second}
		resp, err := client.Do(req)
		if err != nil {
			return nil, err
		}

		data, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			return nil, err
		}

		var result extractRunResponse
		if err := json.Unmarshal(data, &result); err != nil {
			return nil, err
		}

		if result.Status == "PROCESSED" || result.Status == "FAILED" {
			return &result, nil
		}

		time.Sleep(2 * time.Second)
	}
}

func main() {
	filePath := "./sample-declaration.pdf"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}

	apiKey := os.Getenv("EXTEND_API_KEY")
	if apiKey == "" {
		fmt.Println("EXTEND_API_KEY environment variable not set")
		os.Exit(1)
	}

	result, err := processAutoInsuranceDeclarationPage(filePath, apiKey)
	if err != nil {
		fmt.Printf("Fatal error: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("\n=== Full Extraction Output ===")
	output, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(output))
}
// Deploy the "Auto Insurance Declaration Page" pipeline to YOUR Extend account.
//
// The workflow below is fully self-contained — every EXTRACT/CLASSIFY/SPLIT
// step carries its extractor/classifier/splitter config INLINE, so this is a
// single API call. No processors to create or wire up beforehand.
// Idempotent: the created workflow id is cached in .extend/auto-insurance-declaration-page.json,
// so re-running updates the existing workflow instead of duplicating it.
//
// Usage:
//   export EXTEND_API_KEY=sk_...   (from https://dashboard.extend.ai → API Keys)
//   npx tsx provision.ts
//
// Generated by doc1 (template: auto-insurance-declaration-page).

import fs from "node:fs";
import path from "node:path";

const API = "https://api.extend.ai";
const VERSION = "2026-02-09";
const API_KEY = process.env.EXTEND_API_KEY;
if (!API_KEY) { console.error("Set EXTEND_API_KEY first."); process.exit(1); }

const STATE_DIR = path.join(process.cwd(), ".extend");
const STATE_FILE = path.join(STATE_DIR, "auto-insurance-declaration-page.json");

type State = { workflowId?: string };
const state: State = fs.existsSync(STATE_FILE)
  ? JSON.parse(fs.readFileSync(STATE_FILE, "utf8"))
  : {};
function saveState() {
  fs.mkdirSync(STATE_DIR, { recursive: true });
  fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}

async function api(method: string, pathName: string, body?: unknown) {
  const res = await fetch(API + pathName, {
    method,
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "x-extend-api-version": VERSION,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(`${method} ${pathName} failed (${res.status}): ${JSON.stringify(data).slice(0, 300)}`);
  return data;
}

// ── Workflow definition — extractor/classifier/splitter configs inline ──────
const WORKFLOW = {
  "name": "Auto Insurance Declaration Page Processing Pipeline",
  "steps": [
    {
      "name": "startTrigger1",
      "type": "TRIGGER",
      "next": [
        {
          "step": "parse1"
        }
      ]
    },
    {
      "name": "parse1",
      "type": "PARSE",
      "config": {
        "parseConfig": {
          "blockOptions": {
            "text": {
              "agentic": {
                "enabled": true
              }
            }
          },
          "chunkingStrategy": {
            "type": "document"
          }
        }
      },
      "next": [
        {
          "step": "extraction2"
        }
      ]
    },
    {
      "name": "extraction2",
      "type": "EXTRACT",
      "config": {
        "extractorConfig": {
          "schema": {
            "type": "object",
            "required": [
              "vehicles",
              "coverages",
              "discounts",
              "total_fees",
              "named_drivers",
              "policy_number",
              "rating_information",
              "total_policy_premium",
              "policy_effective_date",
              "insurance_company_name",
              "policy_expiration_date",
              "total_policy_premium_and_fees"
            ],
            "properties": {
              "vehicles": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "vin",
                    "coverages",
                    "vehicle_number",
                    "year_make_model"
                  ],
                  "properties": {
                    "vin": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle."
                    },
                    "coverages": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "limit",
                          "deductible",
                          "coverage_type"
                        ],
                        "properties": {
                          "limit": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident')."
                          },
                          "deductible": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "description": "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies."
                          },
                          "coverage_type": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "description": "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc."
                          }
                        },
                        "additionalProperties": false
                      },
                      "description": "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle."
                    },
                    "vehicle_number": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar."
                    },
                    "year_make_model": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The year, make, and model of the insured vehicle. May include body style or trim details."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle."
              },
              "coverages": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "coverage_name",
                    "coverage_limit",
                    "premium_by_vehicle"
                  ],
                  "properties": {
                    "coverage_name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc."
                    },
                    "coverage_limit": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit."
                    },
                    "premium_by_vehicle": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles."
              },
              "discounts": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "discount_type",
                    "applies_to_vehicles"
                  ],
                  "properties": {
                    "discount_type": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc."
                    },
                    "applies_to_vehicles": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount."
              },
              "total_fees": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              },
              "named_drivers": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "driver_name",
                    "driver_status"
                  ],
                  "properties": {
                    "driver_name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The full name of the driver listed on the policy. May include first, middle, and last names."
                    },
                    "driver_status": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers."
              },
              "policy_number": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology."
              },
              "rating_information": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "garaging_zip",
                    "vehicle_usage",
                    "vehicle_number",
                    "current_annual_mileage",
                    "previous_annual_mileage",
                    "years_of_driving_experience"
                  ],
                  "properties": {
                    "garaging_zip": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The ZIP code where the vehicle is primarily garaged or kept."
                    },
                    "vehicle_usage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc."
                    },
                    "vehicle_number": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The reference number or identifier for the vehicle as listed in the rating section."
                    },
                    "current_annual_mileage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The current estimated annual mileage for the vehicle."
                    },
                    "previous_annual_mileage": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The previous year's annual mileage for the vehicle, if available."
                    },
                    "years_of_driving_experience": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The range or number of years of driving experience considered for rating this vehicle."
                    }
                  },
                  "additionalProperties": false
                },
                "description": "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle."
              },
              "total_policy_premium": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              },
              "policy_effective_date": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar.",
                "extend:type": "date"
              },
              "insurance_company_name": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage."
              },
              "policy_expiration_date": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar.",
                "extend:type": "date"
              },
              "total_policy_premium_and_fees": {
                "type": "object",
                "required": [
                  "amount",
                  "iso_4217_currency_code"
                ],
                "properties": {
                  "amount": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "iso_4217_currency_code": {
                    "type": [
                      "string",
                      "null"
                    ]
                  }
                },
                "description": "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar.",
                "extend:type": "currency",
                "additionalProperties": false
              }
            },
            "additionalProperties": false
          },
          "baseProcessor": "extraction_performance",
          "advancedOptions": {
            "reviewAgent": {
              "enabled": true
            },
            "advancedMultimodalEnabled": true
          }
        }
      }
    }
  ]
};

async function main() {
  console.log(`Deploying "${WORKFLOW.name}"…`);

  if (state.workflowId) {
    console.log(`✓ workflow already provisioned (${state.workflowId}) — updating steps`);
    await api("POST", `/workflows/${state.workflowId}`, { steps: WORKFLOW.steps });
  } else {
    // Reuse an existing workflow with the same name if one exists (e.g. a
    // previous run's state file was lost) instead of creating a duplicate.
    try {
      const list = await api("GET", `/workflows?name=${encodeURIComponent(WORKFLOW.name)}`);
      const items = (list.data ?? list.items ?? []) as Array<{ name?: string; id?: string }>;
      const existing = items.find((x) => x.name === WORKFLOW.name);
      if (existing?.id) {
        state.workflowId = existing.id; saveState();
        console.log(`✓ workflow "${WORKFLOW.name}" found in your account (${existing.id}) — updating steps`);
        await api("POST", `/workflows/${existing.id}`, { steps: WORKFLOW.steps });
      }
    } catch { /* lookup is best-effort; fall through to create */ }

    if (!state.workflowId) {
      const created = await api("POST", "/workflows", WORKFLOW);
      const wfId = created.id ?? created.workflow?.id;
      if (!wfId) throw new Error("Could not read created workflow id from response");
      state.workflowId = wfId; saveState();
      console.log(`+ created workflow (${wfId})`);
    }
  }

  // Deploy the current draft as a new version so the workflow is runnable —
  // best-effort: some accounts/plans may not require this explicit step.
  await api("POST", `/workflows/${state.workflowId}/versions`, {}).catch(() => {});

  console.log("\nDone. Run documents through it with:");
  console.log(`  POST ${API}/workflow_runs  { workflow: { id: "${state.workflowId}" }, file: { url: "https://…" } }`);
  console.log("Or open the workflow in the Extend dashboard to review and deploy it.");
}

main().catch((e) => { console.error(e.message ?? e); process.exit(1); });
import os
import json
import sys
from pathlib import Path
from typing import Any

from extend_ai import Extend

API_KEY = os.environ.get("EXTEND_API_KEY")
if not API_KEY:
    print("Set EXTEND_API_KEY first.", file=sys.stderr)
    sys.exit(1)

STATE_DIR = Path.cwd() / ".extend"
STATE_FILE = STATE_DIR / "auto-insurance-declaration-page.json"

state: dict[str, Any] = {}
if STATE_FILE.exists():
    state = json.loads(STATE_FILE.read_text())


def save_state() -> None:
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    STATE_FILE.write_text(json.dumps(state, indent=2))


WORKFLOW = {
    "name": "Auto Insurance Declaration Page Processing Pipeline",
    "steps": [
        {
            "name": "startTrigger1",
            "type": "TRIGGER",
            "next": [{"step": "parse1"}],
        },
        {
            "name": "parse1",
            "type": "PARSE",
            "config": {
                "parseConfig": {
                    "blockOptions": {"text": {"agentic": {"enabled": True}}},
                    "chunkingStrategy": {"type": "document"},
                }
            },
            "next": [{"step": "extraction2"}],
        },
        {
            "name": "extraction2",
            "type": "EXTRACT",
            "config": {
                "extractorConfig": {
                    "schema": {
                        "type": "object",
                        "required": [
                            "vehicles",
                            "coverages",
                            "discounts",
                            "total_fees",
                            "named_drivers",
                            "policy_number",
                            "rating_information",
                            "total_policy_premium",
                            "policy_effective_date",
                            "insurance_company_name",
                            "policy_expiration_date",
                            "total_policy_premium_and_fees",
                        ],
                        "properties": {
                            "vehicles": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": [
                                        "vin",
                                        "coverages",
                                        "vehicle_number",
                                        "year_make_model",
                                    ],
                                    "properties": {
                                        "vin": {
                                            "type": ["string", "null"],
                                            "description": "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle.",
                                        },
                                        "coverages": {
                                            "type": "array",
                                            "items": {
                                                "type": "object",
                                                "required": [
                                                    "limit",
                                                    "deductible",
                                                    "coverage_type",
                                                ],
                                                "properties": {
                                                    "limit": {
                                                        "type": ["string", "null"],
                                                        "description": "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident').",
                                                    },
                                                    "deductible": {
                                                        "type": ["number", "null"],
                                                        "description": "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies.",
                                                    },
                                                    "coverage_type": {
                                                        "type": ["string", "null"],
                                                        "description": "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc.",
                                                    },
                                                },
                                                "additionalProperties": False,
                                            },
                                            "description": "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle.",
                                        },
                                        "vehicle_number": {
                                            "type": ["string", "null"],
                                            "description": "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar.",
                                        },
                                        "year_make_model": {
                                            "type": ["string", "null"],
                                            "description": "The year, make, and model of the insured vehicle. May include body style or trim details.",
                                        },
                                    },
                                    "additionalProperties": False,
                                },
                                "description": "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle.",
                            },
                            "coverages": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": [
                                        "coverage_name",
                                        "coverage_limit",
                                        "premium_by_vehicle",
                                    ],
                                    "properties": {
                                        "coverage_name": {
                                            "type": ["string", "null"],
                                            "description": "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc.",
                                        },
                                        "coverage_limit": {
                                            "type": ["string", "null"],
                                            "description": "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit.",
                                        },
                                        "premium_by_vehicle": {
                                            "type": ["string", "null"],
                                            "description": "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included.",
                                        },
                                    },
                                    "additionalProperties": False,
                                },
                                "description": "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles.",
                            },
                            "discounts": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": ["discount_type", "applies_to_vehicles"],
                                    "properties": {
                                        "discount_type": {
                                            "type": ["string", "null"],
                                            "description": "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc.",
                                        },
                                        "applies_to_vehicles": {
                                            "type": ["string", "null"],
                                            "description": "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'.",
                                        },
                                    },
                                    "additionalProperties": False,
                                },
                                "description": "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount.",
                            },
                            "total_fees": {
                                "type": "object",
                                "required": ["amount", "iso_4217_currency_code"],
                                "properties": {
                                    "amount": {"type": ["number", "null"]},
                                    "iso_4217_currency_code": {"type": ["string", "null"]},
                                },
                                "description": "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar.",
                                "extend:type": "currency",
                                "additionalProperties": False,
                            },
                            "named_drivers": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": ["driver_name", "driver_status"],
                                    "properties": {
                                        "driver_name": {
                                            "type": ["string", "null"],
                                            "description": "The full name of the driver listed on the policy. May include first, middle, and last names.",
                                        },
                                        "driver_status": {
                                            "type": ["string", "null"],
                                            "description": "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations.",
                                        },
                                    },
                                    "additionalProperties": False,
                                },
                                "description": "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers.",
                            },
                            "policy_number": {
                                "type": ["string", "null"],
                                "description": "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology.",
                            },
                            "rating_information": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": [
                                        "garaging_zip",
                                        "vehicle_usage",
                                        "vehicle_number",
                                        "current_annual_mileage",
                                        "previous_annual_mileage",
                                        "years_of_driving_experience",
                                    ],
                                    "properties": {
                                        "garaging_zip": {
                                            "type": ["string", "null"],
                                            "description": "The ZIP code where the vehicle is primarily garaged or kept.",
                                        },
                                        "vehicle_usage": {
                                            "type": ["string", "null"],
                                            "description": "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc.",
                                        },
                                        "vehicle_number": {
                                            "type": ["string", "null"],
                                            "description": "The reference number or identifier for the vehicle as listed in the rating section.",
                                        },
                                        "current_annual_mileage": {
                                            "type": ["string", "null"],
                                            "description": "The current estimated annual mileage for the vehicle.",
                                        },
                                        "previous_annual_mileage": {
                                            "type": ["string", "null"],
                                            "description": "The previous year's annual mileage for the vehicle, if available.",
                                        },
                                        "years_of_driving_experience": {
                                            "type": ["string", "null"],
                                            "description": "The range or number of years of driving experience considered for rating this vehicle.",
                                        },
                                    },
                                    "additionalProperties": False,
                                },
                                "description": "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle.",
                            },
                            "total_policy_premium": {
                                "type": "object",
                                "required": ["amount", "iso_4217_currency_code"],
                                "properties": {
                                    "amount": {"type": ["number", "null"]},
                                    "iso_4217_currency_code": {"type": ["string", "null"]},
                                },
                                "description": "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar.",
                                "extend:type": "currency",
                                "additionalProperties": False,
                            },
                            "policy_effective_date": {
                                "type": ["string", "null"],
                                "description": "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar.",
                                "extend:type": "date",
                            },
                            "insurance_company_name": {
                                "type": ["string", "null"],
                                "description": "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage.",
                            },
                            "policy_expiration_date": {
                                "type": ["string", "null"],
                                "description": "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar.",
                                "extend:type": "date",
                            },
                            "total_policy_premium_and_fees": {
                                "type": "object",
                                "required": ["amount", "iso_4217_currency_code"],
                                "properties": {
                                    "amount": {"type": ["number", "null"]},
                                    "iso_4217_currency_code": {"type": ["string", "null"]},
                                },
                                "description": "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar.",
                                "extend:type": "currency",
                                "additionalProperties": False,
                            },
                        },
                        "additionalProperties": False,
                    },
                    "baseProcessor": "extraction_performance",
                    "advancedOptions": {
                        "reviewAgent": {"enabled": True},
                        "advancedMultimodalEnabled": True,
                    },
                }
            },
        },
    ],
}


async def main() -> None:
    client = Extend(token=API_KEY)

    print(f'Deploying "{WORKFLOW["name"]}…"')

    if state.get("workflowId"):
        workflow_id = state["workflowId"]
        print(f"✓ workflow already provisioned ({workflow_id}) — updating steps")
        await client.workflows.update(
            id=workflow_id, steps=WORKFLOW["steps"]
        )
    else:
        try:
            workflows = await client.workflows.list(
                name=WORKFLOW["name"]
            )
            items = workflows.data if hasattr(workflows, "data") else (workflows.items if hasattr(workflows, "items") else [])
            existing = next(
                (w for w in items if w.name == WORKFLOW["name"]), None
            )
            if existing and existing.id:
                state["workflowId"] = existing.id
                save_state()
                print(
                    f'✓ workflow "{WORKFLOW["name"]}" found in your account ({existing.id}) — updating steps'
                )
                await client.workflows.update(
                    id=existing.id, steps=WORKFLOW["steps"]
                )
        except Exception:
            pass

        if not state.get("workflowId"):
            created = await client.workflows.create(
                name=WORKFLOW["name"], steps=WORKFLOW["steps"]
            )
            workflow_id = created.id
            if not workflow_id:
                raise ValueError(
                    "Could not read created workflow id from response"
                )
            state["workflowId"] = workflow_id
            save_state()
            print(f"+ created workflow ({workflow_id})")

    try:
        await client.workflows.create_version(id=state["workflowId"])
    except Exception:
        pass

    print("\nDone. Run documents through it with:")
    print(
        f'  POST https://api.extend.ai/workflow_runs  {{ "workflow": {{ "id": "{state["workflowId"]}" }}, "file": {{ "url": "https://…" }} }}'
    )
    print(
        "Or open the workflow in the Extend dashboard to review and deploy it."
    )


if __name__ == "__main__":
    import asyncio

    try:
        asyncio.run(main())
    except Exception as e:
        print(str(e) if str(e) else repr(e), file=sys.stderr)
        sys.exit(1)
// Auto Insurance Declaration Page provisioning script for Extend.
// Uses the REST API directly (https://api.extend.ai) because Extend does not publish an official Java SDK.
// This is idempotent: the created workflow id is cached in .extend/auto-insurance-declaration-page.json
// so re-running updates the existing workflow instead of duplicating it.
//
// Usage:
//   export EXTEND_API_KEY=sk_...   (from https://dashboard.extend.ai → API Keys)
//   javac Provision.java && java Provision
//
// Generated by doc1 (template: auto-insurance-declaration-page).

import java.io.IOException;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class Provision {
  private static final String API = "https://api.extend.ai";
  private static final String VERSION = "2026-02-09";
  private static final String API_KEY = System.getenv("EXTEND_API_KEY");
  private static final Path STATE_DIR = Paths.get(System.getProperty("user.dir"), ".extend");
  private static final Path STATE_FILE = STATE_DIR.resolve("auto-insurance-declaration-page.json");

  static {
    if (API_KEY == null || API_KEY.isEmpty()) {
      System.err.println("Set EXTEND_API_KEY first.");
      System.exit(1);
    }
  }

  private static class State {
    String workflowId;
  }

  private static final State state = loadState();

  private static State loadState() {
    State s = new State();
    if (Files.exists(STATE_FILE)) {
      try {
        String content = Files.readString(STATE_FILE);
        if (content.contains("\"workflowId\"")) {
          int start = content.indexOf("\"workflowId\"") + 14;
          int end = content.indexOf("\"", start);
          s.workflowId = content.substring(start, end);
        }
      } catch (IOException e) {
        // Continue with empty state
      }
    }
    return s;
  }

  private static void saveState() throws IOException {
    Files.createDirectories(STATE_DIR);
    String json = String.format("{\n  \"workflowId\": \"%s\"\n}", state.workflowId);
    Files.writeString(STATE_FILE, json);
  }

  private static String api(String method, String pathName, String body) throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest.Builder builder = HttpRequest.newBuilder()
        .uri(java.net.URI.create(API + pathName))
        .header("Authorization", "Bearer " + API_KEY)
        .header("x-extend-api-version", VERSION)
        .method(method, body != null ? HttpRequest.BodyPublishers.ofString(body) : HttpRequest.BodyPublishers.noBody());
    if (body != null) {
      builder.header("Content-Type", "application/json");
    }
    HttpRequest request = builder.build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() < 200 || response.statusCode() >= 300) {
      String preview = response.body().length() > 300 ? response.body().substring(0, 300) : response.body();
      throw new RuntimeException(method + " " + pathName + " failed (" + response.statusCode() + "): " + preview);
    }
    return response.body();
  }

  private static String buildWorkflowJson() {
    StringBuilder sb = new StringBuilder();
    sb.append("{\"name\":\"Auto Insurance Declaration Page Processing Pipeline\",");
    sb.append("\"steps\":[");
    
    // startTrigger1
    sb.append("{\"name\":\"startTrigger1\",\"type\":\"TRIGGER\",\"next\":[{\"step\":\"parse1\"}]},");
    
    // parse1
    sb.append("{\"name\":\"parse1\",\"type\":\"PARSE\",");
    sb.append("\"config\":{\"parseConfig\":{");
    sb.append("\"blockOptions\":{\"text\":{\"agentic\":{\"enabled\":true}}},");
    sb.append("\"chunkingStrategy\":{\"type\":\"document\"}");
    sb.append("}},\"next\":[{\"step\":\"extraction2\"}]},");
    
    // extraction2 with full schema
    sb.append("{\"name\":\"extraction2\",\"type\":\"EXTRACT\",");
    sb.append("\"config\":{\"extractorConfig\":{");
    sb.append("\"schema\":{");
    sb.append("\"type\":\"object\",");
    sb.append("\"required\":[\"vehicles\",\"coverages\",\"discounts\",\"total_fees\",\"named_drivers\",\"policy_number\",\"rating_information\",\"total_policy_premium\",\"policy_effective_date\",\"insurance_company_name\",\"policy_expiration_date\",\"total_policy_premium_and_fees\"],");
    sb.append("\"properties\":{");
    
    // vehicles property
    sb.append("\"vehicles\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"vin\",\"coverages\",\"vehicle_number\",\"year_make_model\"],\"properties\":{");
    sb.append("\"vin\":{\"type\":[\"string\",\"null\"],\"description\":\"The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle.\"},");
    sb.append("\"coverages\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"limit\",\"deductible\",\"coverage_type\"],\"properties\":{");
    sb.append("\"limit\":{\"type\":[\"string\",\"null\"],\"description\":\"The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident').\"},");
    sb.append("\"deductible\":{\"type\":[\"number\",\"null\"],\"description\":\"The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies.\"},");
    sb.append("\"coverage_type\":{\"type\":[\"string\",\"null\"],\"description\":\"The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle.\"},");
    sb.append("\"vehicle_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar.\"},");
    sb.append("\"year_make_model\":{\"type\":[\"string\",\"null\"],\"description\":\"The year, make, and model of the insured vehicle. May include body style or trim details.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle.\"},");
    
    // coverages property
    sb.append("\"coverages\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"coverage_name\",\"coverage_limit\",\"premium_by_vehicle\"],\"properties\":{");
    sb.append("\"coverage_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc.\"},");
    sb.append("\"coverage_limit\":{\"type\":[\"string\",\"null\"],\"description\":\"The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit.\"},");
    sb.append("\"premium_by_vehicle\":{\"type\":[\"string\",\"null\"],\"description\":\"The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles.\"},");
    
    // discounts property
    sb.append("\"discounts\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"discount_type\",\"applies_to_vehicles\"],\"properties\":{");
    sb.append("\"discount_type\":{\"type\":[\"string\",\"null\"],\"description\":\"The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc.\"},");
    sb.append("\"applies_to_vehicles\":{\"type\":[\"string\",\"null\"],\"description\":\"The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount.\"},");
    
    // total_fees property
    sb.append("\"total_fees\":{\"type\":\"object\",\"required\":[\"amount\",\"iso_4217_currency_code\"],\"properties\":{");
    sb.append("\"amount\":{\"type\":[\"number\",\"null\"]},");
    sb.append("\"iso_4217_currency_code\":{\"type\":[\"string\",\"null\"]}");
    sb.append("},\"description\":\"The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar.\",\"extend:type\":\"currency\",\"additionalProperties\":false},");
    
    // named_drivers property
    sb.append("\"named_drivers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"driver_name\",\"driver_status\"],\"properties\":{");
    sb.append("\"driver_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The full name of the driver listed on the policy. May include first, middle, and last names.\"},");
    sb.append("\"driver_status\":{\"type\":[\"string\",\"null\"],\"description\":\"The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers.\"},");
    
    // policy_number property
    sb.append("\"policy_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology.\"},");
    
    // rating_information property
    sb.append("\"rating_information\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"garaging_zip\",\"vehicle_usage\",\"vehicle_number\",\"current_annual_mileage\",\"previous_annual_mileage\",\"years_of_driving_experience\"],\"properties\":{");
    sb.append("\"garaging_zip\":{\"type\":[\"string\",\"null\"],\"description\":\"The ZIP code where the vehicle is primarily garaged or kept.\"},");
    sb.append("\"vehicle_usage\":{\"type\":[\"string\",\"null\"],\"description\":\"The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc.\"},");
    sb.append("\"vehicle_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The reference number or identifier for the vehicle as listed in the rating section.\"},");
    sb.append("\"current_annual_mileage\":{\"type\":[\"string\",\"null\"],\"description\":\"The current estimated annual mileage for the vehicle.\"},");
    sb.append("\"previous_annual_mileage\":{\"type\":[\"string\",\"null\"],\"description\":\"The previous year's annual mileage for the vehicle, if available.\"},");
    sb.append("\"years_of_driving_experience\":{\"type\":[\"string\",\"null\"],\"description\":\"The range or number of years of driving experience considered for rating this vehicle.\"}");
    sb.append("},\"additionalProperties\":false},\"description\":\"A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle.\"},");
    
    // total_policy_premium property
    sb.append("\"total_policy_premium\":{\"type\":\"object\",\"required\":[\"amount\",\"iso_4217_currency_code\"],\"properties\":{");
    sb.append("\"amount\":{\"type\":[\"number\",\"null\"]},");
    sb.append("\"iso_4217_currency_code\":{\"type\":[\"string\",\"null\"]}");
    sb.append("},\"description\":\"The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar.\",\"extend:type\":\"currency\",\"additionalProperties\":false},");
    
    // policy_effective_date property
    sb.append("\"policy_effective_date\":{\"type\":[\"string\",\"null\"],\"description\":\"The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar.\",\"extend:type\":\"date\"},");
    
    // insurance_company_name property
    sb.append("\"insurance_company_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage.\"},");
    
    // policy_expiration_date property
    sb.append("\"policy_expiration_date\":{\"type\":[\"string\",\"null\"],\"description\":\"The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar.\",\"extend:type\":\"date\"},");
    
    // total_policy_premium_and_fees property
    sb.append("\"total_policy_premium_and_fees\":{\"type\":\"object\",\"required\":[\"amount\",\"iso_4217_currency_code\"],\"properties\":{");
    sb.append("\"amount\":{\"type\":[\"number\",\"null\"]},");
    sb.append("\"iso_4217_currency_code\":{\"type\":[\"string\",\"null\"]}");
    sb.append("},\"description\":\"The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar.\",\"extend:type\":\"currency\",\"additionalProperties\":false}");
    
    sb.append("},\"additionalProperties\":false}");
    sb.append("},\"baseProcessor\":\"extraction_performance\",");
    sb.append("\"advancedOptions\":{\"reviewAgent\":{\"enabled\":true},\"advancedMultimodalEnabled\":true}");
    sb.append("}}}]}");
    return sb.toString();
  }

  private static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("Deploying \"Auto Insurance Declaration Page Processing Pipeline\"…");

    if (state.workflowId != null && !state.workflowId.isEmpty()) {
      System.out.println("✓ workflow already provisioned (" + state.workflowId + ") — updating steps");
      String stepsBody = "{\"steps\":" + buildWorkflowJson().substring(buildWorkflowJson().indexOf("\"steps\"") + 9, buildWorkflowJson().lastIndexOf("}") + 1) + "}";
      api("POST", "/workflows/" + state.workflowId, stepsBody);
    } else {
      // Try to find existing workflow by name
      boolean found = false;
      try {
        String encoded = URLEncoder.encode("Auto Insurance Declaration Page Processing Pipeline", StandardCharsets.UTF_8);
        String response = api("GET", "/workflows?name=" + encoded, null);
        if (response.contains("\"id\"")) {
          int idIdx = response.indexOf("\"id\"");
          if (idIdx > 0) {
            int start = response.indexOf("\"", idIdx + 5) + 1;
            int end = response.indexOf("\"", start);
            if (start > 0 && end > start) {
              String existingId = response.substring(start, end);
              state.workflowId = existingId;
              saveState();
              found = true;
              System.out.println("✓ workflow \"Auto Insurance Declaration Page Processing Pipeline\" found in your account (" + existingId + ") — updating steps");
              String stepsBody = "{\"steps\":" + buildWorkflowJson().substring(buildWorkflowJson().indexOf("\"steps\"") + 9, buildWorkflowJson().lastIndexOf("}") + 1) + "}";
              api("POST", "/workflows/" + existingId, stepsBody);
            }
          }
        }
      } catch (Exception e) {
        // Lookup is best-effort; fall through to create
      }

      if (!found) {
        String workflowJson = buildWorkflowJson();
        String response = api("POST", "/workflows", workflowJson);
        String wfId = null;
        if (response.contains("\"id\"")) {
          int idIdx = response.indexOf("\"id\"");
          int start = response.indexOf("\"", idIdx + 5) + 1;
          int end = response.indexOf("\"", start);
          if (start > 0 && end > start) {
            wfId = response.substring(start, end);
          }
        }
        if (wfId == null || wfId.isEmpty()) {
          throw new RuntimeException("Could not read created workflow id from response");
        }
        state.workflowId = wfId;
        saveState();
        System.out.println("+ created workflow (" + wfId + ")");
      }
    }

    // Deploy the current draft as a new version so the workflow is runnable
    try {
      api("POST", "/workflows/" + state.workflowId + "/versions", "{}");
    } catch (Exception e) {
      // Best-effort: some accounts/plans may not require this explicit step
    }

    System.out.println("\nDone. Run documents through it with:");
    System.out.println("  POST " + API + "/workflow_runs  { workflow: { id: \"" + state.workflowId + "\" }, file: { url: \"https://…\" } }");
    System.out.println("Or open the workflow in the Extend dashboard to review and deploy it.");
  }
}
// This script uses Extend's REST API directly (https://api.extend.ai)
// because Extend has no official Go SDK yet.
//
// Deploy the "Auto Insurance Declaration Page" pipeline to YOUR Extend account.
//
// The workflow below is fully self-contained — every EXTRACT/CLASSIFY/SPLIT
// step carries its extractor/classifier/splitter config INLINE, so this is a
// single API call. No processors to create or wire up beforehand.
// Idempotent: the created workflow id is cached in .extend/auto-insurance-declaration-page.json,
// so re-running updates the existing workflow instead of duplicating it.
//
// Usage:
//   export EXTEND_API_KEY=sk_...   (from https://dashboard.extend.ai → API Keys)
//   go run provision.go
//
// Generated by doc1 (template: auto-insurance-declaration-page).

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
)

const (
	API     = "https://api.extend.ai"
	VERSION = "2026-02-09"
)

type State struct {
	WorkflowID string `json:"workflowId,omitempty"`
}

var stateDir = filepath.Join(".", ".extend")
var stateFile = filepath.Join(stateDir, "auto-insurance-declaration-page.json")

func loadState() (State, error) {
	data, err := os.ReadFile(stateFile)
	if err != nil {
		if os.IsNotExist(err) {
			return State{}, nil
		}
		return State{}, err
	}
	var s State
	if err := json.Unmarshal(data, &s); err != nil {
		return State{}, err
	}
	return s, nil
}

func saveState(s State) error {
	if err := os.MkdirAll(stateDir, 0755); err != nil {
		return err
	}
	data, err := json.MarshalIndent(s, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(stateFile, data, 0644)
}

func apiCall(method, pathName string, body interface{}) (map[string]interface{}, error) {
	var reqBody io.Reader
	if body != nil {
		data, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}
		reqBody = bytes.NewReader(data)
	}

	req, err := http.NewRequest(method, API+pathName, reqBody)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", os.Getenv("EXTEND_API_KEY")))
	req.Header.Set("x-extend-api-version", VERSION)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	respData, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var result map[string]interface{}
	_ = json.Unmarshal(respData, &result)

	if resp.StatusCode >= 400 {
		preview := string(respData)
		if len(preview) > 300 {
			preview = preview[:300]
		}
		return nil, fmt.Errorf("%s %s failed (%d): %s", method, pathName, resp.StatusCode, preview)
	}

	return result, nil
}

func getWorkflowID(result map[string]interface{}) string {
	if id, ok := result["id"].(string); ok {
		return id
	}
	if workflow, ok := result["workflow"].(map[string]interface{}); ok {
		if id, ok := workflow["id"].(string); ok {
			return id
		}
	}
	return ""
}

func extractWorkflowItems(result map[string]interface{}) []map[string]interface{} {
	if data, ok := result["data"].([]interface{}); ok {
		items := make([]map[string]interface{}, 0, len(data))
		for _, d := range data {
			if item, ok := d.(map[string]interface{}); ok {
				items = append(items, item)
			}
		}
		return items
	}
	if items, ok := result["items"].([]interface{}); ok {
		itemsArr := make([]map[string]interface{}, 0, len(items))
		for _, i := range items {
			if item, ok := i.(map[string]interface{}); ok {
				itemsArr = append(itemsArr, item)
			}
		}
		return itemsArr
	}
	return []map[string]interface{}{}
}

func main() {
	apiKey := os.Getenv("EXTEND_API_KEY")
	if apiKey == "" {
		fmt.Fprintf(os.Stderr, "Set EXTEND_API_KEY first.\n")
		os.Exit(1)
	}

	state, err := loadState()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error loading state: %v\n", err)
		os.Exit(1)
	}

	workflow := map[string]interface{}{
		"name": "Auto Insurance Declaration Page Processing Pipeline",
		"steps": []interface{}{
			map[string]interface{}{
				"name": "startTrigger1",
				"type": "TRIGGER",
				"next": []interface{}{
					map[string]interface{}{"step": "parse1"},
				},
			},
			map[string]interface{}{
				"name": "parse1",
				"type": "PARSE",
				"config": map[string]interface{}{
					"parseConfig": map[string]interface{}{
						"blockOptions": map[string]interface{}{
							"text": map[string]interface{}{
								"agentic": map[string]interface{}{
									"enabled": true,
								},
							},
						},
						"chunkingStrategy": map[string]interface{}{
							"type": "document",
						},
					},
				},
				"next": []interface{}{
					map[string]interface{}{"step": "extraction2"},
				},
			},
			map[string]interface{}{
				"name": "extraction2",
				"type": "EXTRACT",
				"config": map[string]interface{}{
					"extractorConfig": map[string]interface{}{
						"schema": getExtractionSchema(),
						"baseProcessor": "extraction_performance",
						"advancedOptions": map[string]interface{}{
							"reviewAgent": map[string]interface{}{
								"enabled": true,
							},
							"advancedMultimodalEnabled": true,
						},
					},
				},
			},
		},
	}

	fmt.Printf("Deploying \"%s\"…\n", workflow["name"])

	if state.WorkflowID != "" {
		fmt.Printf("✓ workflow already provisioned (%s) — updating steps\n", state.WorkflowID)
		_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", state.WorkflowID), map[string]interface{}{
			"steps": workflow["steps"],
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error updating workflow: %v\n", err)
			os.Exit(1)
		}
	} else {
		// Try to find existing workflow by name
		query := url.QueryEscape(workflow["name"].(string))
		list, err := apiCall("GET", fmt.Sprintf("/workflows?name=%s", query), nil)
		if err == nil {
			items := extractWorkflowItems(list)
			for _, item := range items {
				if name, ok := item["name"].(string); ok && name == workflow["name"] {
					if id, ok := item["id"].(string); ok {
						state.WorkflowID = id
						_ = saveState(state)
						fmt.Printf("✓ workflow \"%s\" found in your account (%s) — updating steps\n", workflow["name"], id)
						_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", id), map[string]interface{}{
							"steps": workflow["steps"],
						})
						if err != nil {
							fmt.Fprintf(os.Stderr, "Error updating workflow: %v\n", err)
							os.Exit(1)
						}
						break
					}
				}
			}
		}

		if state.WorkflowID == "" {
			created, err := apiCall("POST", "/workflows", workflow)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error creating workflow: %v\n", err)
				os.Exit(1)
			}
			wfID := getWorkflowID(created)
			if wfID == "" {
				fmt.Fprintf(os.Stderr, "Could not read created workflow id from response\n")
				os.Exit(1)
			}
			state.WorkflowID = wfID
			if err := saveState(state); err != nil {
				fmt.Fprintf(os.Stderr, "Error saving state: %v\n", err)
				os.Exit(1)
			}
			fmt.Printf("+ created workflow (%s)\n", wfID)
		}
	}

	// Deploy the current draft as a new version so the workflow is runnable —
	// best-effort: some accounts/plans may not require this explicit step.
	_, _ = apiCall("POST", fmt.Sprintf("/workflows/%s/versions", state.WorkflowID), map[string]interface{}{})

	fmt.Printf("\nDone. Run documents through it with:\n")
	fmt.Printf("  POST %s/workflow_runs  { workflow: { id: \"%s\" }, file: { url: \"https://…\" } }\n", API, state.WorkflowID)
	fmt.Printf("Or open the workflow in the Extend dashboard to review and deploy it.\n")
}

func getExtractionSchema() map[string]interface{} {
	return map[string]interface{}{
		"type": "object",
		"required": []string{
			"vehicles", "coverages", "discounts", "total_fees", "named_drivers",
			"policy_number", "rating_information", "total_policy_premium",
			"policy_effective_date", "insurance_company_name", "policy_expiration_date",
			"total_policy_premium_and_fees",
		},
		"properties": map[string]interface{}{
			"vehicles": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"required": []string{"vin", "coverages", "vehicle_number", "year_make_model"},
					"properties": map[string]interface{}{
						"vin": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The Vehicle Identification Number (VIN) for the insured vehicle. This is a unique alphanumeric code assigned to each vehicle.",
						},
						"coverages": map[string]interface{}{
							"type": "array",
							"items": map[string]interface{}{
								"type":     "object",
								"required": []string{"limit", "deductible", "coverage_type"},
								"properties": map[string]interface{}{
									"limit": map[string]interface{}{
										"type":        []string{"string", "null"},
										"description": "The coverage limit for this specific coverage, if applicable. May be a monetary value or descriptive limit (e.g., '$500,000 each accident').",
									},
									"deductible": map[string]interface{}{
										"type":        []string{"number", "null"},
										"description": "The deductible amount for this specific coverage, if applicable. This is the amount the policyholder must pay out of pocket before insurance applies.",
									},
									"coverage_type": map[string]interface{}{
										"type":        []string{"string", "null"},
										"description": "The type of insurance coverage applied to this vehicle, such as 'Comprehensive', 'Collision', 'Liability', etc.",
									},
								},
								"additionalProperties": false,
							},
							"description": "A list of coverage types and details specific to this vehicle. Each entry represents a coverage applied to the vehicle.",
						},
						"vehicle_number": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The reference number or identifier for the vehicle as listed on the policy, such as 'Vehicle 1', 'Veh. #', or similar.",
						},
						"year_make_model": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The year, make, and model of the insured vehicle. May include body style or trim details.",
						},
					},
					"additionalProperties": false,
				},
				"description": "A list of all vehicles covered by this policy. Each entry contains identifying and coverage information for a specific vehicle.",
			},
			"coverages": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type":     "object",
					"required": []string{"coverage_name", "coverage_limit", "premium_by_vehicle"},
					"properties": map[string]interface{}{
						"coverage_name": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The name or type of insurance coverage, such as 'Bodily Injury Liability', 'Property Damage Liability', 'Comprehensive', etc.",
						},
						"coverage_limit": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The maximum amount payable under this coverage. May be expressed per person, per accident, or as a descriptive limit.",
						},
						"premium_by_vehicle": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The premium amount charged for this coverage, typically broken down by vehicle. May be a monetary value or indicate if included.",
						},
					},
					"additionalProperties": false,
				},
				"description": "A list of all insurance coverages provided by this policy, including limits and premiums for each coverage type. Each entry represents a distinct coverage, which may apply to all or specific vehicles.",
			},
			"discounts": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type":     "object",
					"required": []string{"discount_type", "applies_to_vehicles"},
					"properties": map[string]interface{}{
						"discount_type": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The name or description of the discount applied, such as 'Good Driver', 'Multi-Car', 'Anti-Lock Brakes', etc.",
						},
						"applies_to_vehicles": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The vehicle numbers or identifiers to which this discount applies. May be a single vehicle, a list, or 'All'.",
						},
					},
					"additionalProperties": false,
				},
				"description": "A list of discounts applied to the policy, including the type of discount and the vehicles to which it applies. Each entry represents a specific discount.",
			},
			"total_fees": map[string]interface{}{
				"type":     "object",
				"required": []string{"amount", "iso_4217_currency_code"},
				"properties": map[string]interface{}{
					"amount": map[string]interface{}{
						"type": []string{"number", "null"},
					},
					"iso_4217_currency_code": map[string]interface{}{
						"type": []string{"string", "null"},
					},
				},
				"description":         "The total amount of additional fees applied to the policy, such as anti-fraud fees or administrative charges. This is the sum of all non-premium fees. May be labeled as 'Fees', 'Policy Fees', or similar.",
				"extend:type":         "currency",
				"additionalProperties": false,
			},
			"named_drivers": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type":     "object",
					"required": []string{"driver_name", "driver_status"},
					"properties": map[string]interface{}{
						"driver_name": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The full name of the driver listed on the policy. May include first, middle, and last names.",
						},
						"driver_status": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The coverage status of the driver under this policy, such as 'Covered', 'Excluded', or other designations.",
						},
					},
					"additionalProperties": false,
				},
				"description": "A list of all individuals who are covered to drive vehicles under this policy. Each entry represents a named driver, including their name and driver status. May include primary, occasional, or excluded drivers.",
			},
			"policy_number": map[string]interface{}{
				"type":        []string{"string", "null"},
				"description": "The unique identifier assigned to this auto insurance policy. This is the primary reference number for the policy and may include numbers, letters, or special characters. Commonly labeled as 'Policy Number', 'Policy No.', or similar terminology.",
			},
			"rating_information": map[string]interface{}{
				"type": "array",
				"items": map[string]interface{}{
					"type": "object",
					"required": []string{
						"garaging_zip", "vehicle_usage", "vehicle_number",
						"current_annual_mileage", "previous_annual_mileage", "years_of_driving_experience",
					},
					"properties": map[string]interface{}{
						"garaging_zip": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The ZIP code where the vehicle is primarily garaged or kept.",
						},
						"vehicle_usage": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The primary use of the vehicle, such as 'Commuter Use', 'Pleasure', 'Business', etc.",
						},
						"vehicle_number": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The reference number or identifier for the vehicle as listed in the rating section.",
						},
						"current_annual_mileage": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The current estimated annual mileage for the vehicle.",
						},
						"previous_annual_mileage": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The previous year's annual mileage for the vehicle, if available.",
						},
						"years_of_driving_experience": map[string]interface{}{
							"type":        []string{"string", "null"},
							"description": "The range or number of years of driving experience considered for rating this vehicle.",
						},
					},
					"additionalProperties": false,
				},
				"description": "A list of rating factors and details used to determine premiums for each vehicle. Each entry represents a rating detail for a specific vehicle.",
			},
			"total_policy_premium": map[string]interface{}{
				"type":     "object",
				"required": []string{"amount", "iso_4217_currency_code"},
				"properties": map[string]interface{}{
					"amount": map[string]interface{}{
						"type": []string{"number", "null"},
					},
					"iso_4217_currency_code": map[string]interface{}{
						"type": []string{"string", "null"},
					},
				},
				"description":         "The total premium amount charged for the entire policy period, before any additional fees or discounts. This is the sum of all premiums for all vehicles and coverages. May be labeled as 'Policy Premium', 'Total Premium', or similar.",
				"extend:type":         "currency",
				"additionalProperties": false,
			},
			"policy_effective_date": map[string]interface{}{
				"type":        []string{"string", "null"},
				"description": "The date and time when the insurance policy coverage begins. This marks the start of the policy period. May be labeled as 'Effective Date', 'Policy Start', or similar.",
				"extend:type": "date",
			},
			"insurance_company_name": map[string]interface{}{
				"type":        []string{"string", "null"},
				"description": "The name of the insurance company providing this policy. This is the issuing or underwriting company responsible for coverage.",
			},
			"policy_expiration_date": map[string]interface{}{
				"type":        []string{"string", "null"},
				"description": "The date and time when the insurance policy coverage ends. This marks the end of the policy period. May be labeled as 'Expiration Date', 'Policy End', or similar.",
				"extend:type": "date",
			},
			"total_policy_premium_and_fees": map[string]interface{}{
				"type":     "object",
				"required": []string{"amount", "iso_4217_currency_code"},
				"properties": map[string]interface{}{
					"amount": map[string]interface{}{
						"type": []string{"number", "null"},
					},
					"iso_4217_currency_code": map[string]interface{}{
						"type": []string{"string", "null"},
					},
				},
				"description":         "The combined total of all premiums and fees for the policy period. This represents the full amount due for coverage, before discounts. May be labeled as 'Policy Premium and Fees', 'Total Policy Cost', or similar.",
				"extend:type":         "currency",
				"additionalProperties": false,
			},
		},
		"additionalProperties": false,
	}
}

Frequently Asked Questions (FAQ)

For critical fields (policy number, VIN, coverage limits), require `confidence >= 0.92`; for secondary fields (agent name, phone), `>= 0.85` is acceptable. Test against 10–20 real samples from each insurer to tune thresholds, since declaration layouts vary widely.
Tags
InsuranceAutoPolicyDeclaration
About this template

An Auto Insurance Declaration Page summarizes active insurance policy details including effective/expiration dates, premium costs, covered household drivers, insured vehicles with VINs, and coverage types with limits and deductibles. This template extracts and structures this information as JSON.

Document formats
  • PDF
  • Images & Scans
Requirements
  • Long tables
  • Checkboxes & Strikethroughs