# Implementation Plan: Versioned JSON Artifact Importer (LEAD-GEN)

---

## 1. Goal & Architectural Overview

The objective is to implement a robust, domain-agnostic, and idempotent **Versioned JSON Artifact Importer** that ingests factory-generated output artifacts into the target Lead Generation storage system without writing directly to the upstream Factory database.

### Core Architectural Principles
- **No Direct Factory DB Writes**: Ingestion is decoupled; it reads immutable serialized artifact files emitted by upstream pipeline steps and writes exclusively to the local Lead Generation data store (e.g., SQLite/PostgreSQL target DB or versioned lead repository).
- **Idempotency**: Running repeated imports of the same artifact—or subsequent runs with identical content—guarantees exact matching company and lead entity counts without duplication or phantom updates.
- **Data Provenance & Checksums**: Every imported record retains explicit tracking back to the source artifact file, SHA-256 hash, pipeline run ID, source timestamp, and campaign identifier.
- **Atomic Operations**: Ingestion transactions use all-or-nothing atomicity (staged staging tables or transactional boundary with rollback on validation or I/O failure).
- **Domain-Agnostic Design**: Schema contracts validate structural integrity, evidence attachments, and provenance fields without hard-coding specific industries, geographies, or vendors.

---

## 2. Artifact Schema & Contract Specification

Artifacts produced by the Factory adhere to versioned schema specifications (e.g., `leadgen_artifact_v1.json`).

### Schema Structure (`schema_version: "1.0.0"`)
```json
{
  "schema_version": "1.0.0",
  "artifact_id": "art-20261008-eu-licensing-001",
  "campaign_id": "LEAD-001.1",
  "generated_at": "2026-10-08T20:00:00Z",
  "generator_metadata": {
    "engine_version": "0.1.0",
    "source_file": "pilot-campaign-definition-v1.md"
  },
  "records": [
    {
      "company": {
        "external_id": "comp-nordic-logistics-corp",
        "name": "Nordic Logistics Group",
        "domain": "nordiclogistics.example.com",
        "country": "SE",
        "industry": "Transport & Logistics",
        "size_bracket": "5000-10000"
      },
      "leads": [
        {
          "external_id": "lead-nlg-it-dir-01",
          "title": "Director of Enterprise IT Architecture",
          "role_category": "Decision Maker - IT Estate",
          "location": "Sweden",
          "evidence": [
            {
              "type": "software_estate_signal",
              "source_url": "https://nordiclogistics.example.com/press/cloud-transformation",
              "discovered_at": "2026-10-01T12:00:00Z",
              "snippet": "Transitioning legacy Oracle and SAP enterprise agreements to multi-cloud..."
            }
          ],
          "qualification_notes": "Meets pilot requirement: enterprise software estate optimization demand."
        }
      ]
    }
  ]
}
```

---

## 3. Importer Component Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Factory Output                         │
│             data/artifacts/LEAD-GEN/.../*.json              │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                  Artifact Reader & Checksum                 │
│  - Reads raw JSON bytes                                     │
│  - Calculates SHA-256 digest                                │
│  - Verifies read integrity                                  │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                 Validator & Schema Enforcer                 │
│  - JSON Schema contract validation                          │
│  - Mandatory provenance & evidence check                    │
│  - Emits Quarantine Report on failure                       │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│            Atomic Ingestion Engine (Transaction)            │
│  - Begins target DB transaction                             │
│  - Records artifact import log (artifact_id, sha256, time)  │
│  - Upserts Companies (keyed by normalized domain/id)        │
│  - Upserts Leads (keyed by company_id + external_id)        │
│  - Records Evidence links & provenance metadata             │
│  - Commits transaction (or Rollback on error)               │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                 Target Lead Store / DB                      │
│     tables: artifacts, companies, leads, lead_evidence      │
└─────────────────────────────────────────────────────────────┘
```

### Module Breakdown

1. **`checksum.py`**:
   - Computes standard SHA-256 for file contents before deserialization.
   - Compares with stored checksum in target catalog table `imported_artifacts` to detect exact duplicate artifacts vs. mutated files with conflicting versions.

2. **`validator.py`**:
   - Uses strict schema validation (using Pydantic models or JSON Schema).
   - Validates existence of mandatory provenance: `campaign_id`, `generated_at`, `evidence[].source_url`, `evidence[].discovered_at`.
   - Rejects schema violations and outputs actionable, structured error reports (file path, line/field path, expected vs. received).

3. **`deduplicator.py` (Idempotency Engine)**:
   - Primary entity keys:
     - **Company**: Natural key `normalized_domain` (falling back to `external_id`).
     - **Lead**: Compound key `(company_id, external_id)` or `(company_id, normalized_title_role)`.
   - Merge strategy: deterministic upsert without duplicating count statistics. If a record is imported again with identical attributes, the row state remains stable.

4. **`atomic_writer.py`**:
   - Manages relational database transactional boundaries (`BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`).
   - If using a file-based storage fallback, writes to a temporary atomic staging directory (`.tmp_<uuid>`) and renames atomically upon completion.
   - Ensures no direct writes occur to the Factory database; all operations target the lead repository database.

5. **`reporter.py`**:
   - Formats CLI and log outputs with import diagnostics:
     - Artifact SHA-256 and ID.
     - Processed records, new companies created, existing companies matched, leads added/updated, rejected records.

---

## 4. Database Schema (Target Lead Store)

```sql
CREATE TABLE IF NOT EXISTS imported_artifacts (
    artifact_id TEXT PRIMARY KEY,
    checksum_sha256 TEXT NOT NULL,
    campaign_id TEXT NOT NULL,
    schema_version TEXT NOT NULL,
    source_path TEXT NOT NULL,
    imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    records_count INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS companies (
    id TEXT PRIMARY KEY,
    external_id TEXT UNIQUE,
    normalized_domain TEXT UNIQUE,
    name TEXT NOT NULL,
    country TEXT,
    industry TEXT,
    size_bracket TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS leads (
    id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
    external_id TEXT NOT NULL,
    title TEXT NOT NULL,
    role_category TEXT,
    location TEXT,
    qualification_notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(company_id, external_id)
);

CREATE TABLE IF NOT EXISTS lead_evidence (
    id TEXT PRIMARY KEY,
    lead_id TEXT NOT NULL REFERENCES leads(id) ON DELETE CASCADE,
    evidence_type TEXT NOT NULL,
    source_url TEXT NOT NULL,
    discovered_at TIMESTAMP NOT NULL,
    snippet TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

---

## 5. Execution Pipeline (Step-by-Step Flow)

1. **Intake & Verification**:
   - Input artifact file path is resolved.
   - Read byte stream and compute SHA-256 digest.
   - Check `imported_artifacts` table:
     - If the identical `artifact_id` and `checksum_sha256` have already been fully imported, return an idempotent success summary indicating no new insertions needed.
     - If `artifact_id` matches but checksum differs, fail with a version conflict error unless an explicit `--force-reimport` or patch version is provided.

2. **Deserialization & Validation**:
   - Parse JSON into structured schema.
   - Run validation rules:
     - Check semantic types (valid ISO 8601 timestamps, non-empty URLs, required role classifications).
   - If validation errors are found:
     - Collect all violations into a structured error manifest.
     - Abort the transaction before touching domain tables.

3. **Atomic Execution**:
   - Open database transaction.
   - Insert/update metadata into `imported_artifacts`.
   - Iterate over companies:
     - Query existing company by `normalized_domain` / `external_id`.
     - Insert or update company record.
   - Iterate over leads:
     - Query existing lead by `(company_id, external_id)`.
     - Insert or update lead record.
     - Upsert associated evidence items.
   - Commit transaction.

4. **Metrics & Summary**:
   - Return structured status object:
     `{ "status": "SUCCESS", "companies_total": N, "leads_total": M, "companies_created": 0, "leads_created": 0 }`.

---

## 6. Verification & Repeat Import Test Plan

### Acceptance Criterion
> **"Two imports yield same company/lead counts"**

### Test Cases

1. **Test: Double Import Idempotency (Repeat Import)**
   - **Procedure**:
     1. Initialize empty test target database.
     2. Ingest `test_artifact_sample_01.json` containing 5 companies and 10 leads.
     3. Record database metrics: `COUNT(*) FROM companies` = 5, `COUNT(*) FROM leads` = 10.
     4. Execute the importer a second time using the exact same artifact.
     5. Query database counts again.
   - **Expected Outcome**:
     - `COUNT(*) FROM companies` remains exactly 5.
     - `COUNT(*) FROM leads` remains exactly 10.
     - No duplicate key violations or transaction aborts.

2. **Test: Atomic Rollback on Corrupted Record**
   - **Procedure**:
     1. Prepare an artifact containing 3 valid records and 1 record missing mandatory `source_url` evidence.
     2. Execute importer against target DB.
   - **Expected Outcome**:
     - Validator throws structured validation error.
     - Transaction rolls back completely; target database table counts remain 0.

3. **Test: Isolation from Factory DB**
   - **Procedure**:
     1. Run integration test in an environment where Factory DB credentials/paths are nonexistent or explicitly blocked.
   - **Expected Outcome**:
     - Import succeeds relying exclusively on local target storage and the input JSON artifact file.

4. **Test: Provenance Linkage Verification**
   - **Procedure**:
     1. Inspect `lead_evidence` and `imported_artifacts` after successful execution.
   - **Expected Outcome**:
     - Every lead references verifiable source URLs, discovered timestamps, and the parent artifact SHA-256.