"""Result streaming module for formatting and serializing records."""

import copy
import json


def stream_results(records: list[dict], template: dict) -> list[str]:
    """Format records by merging with a template, return as JSON lines.

    Each record is merged onto a copy of the template so that template
    fields act as defaults. Results are validated by round-tripping
    through JSON to catch non-serializable values early.
    """
    output = []
    for record in records:
        result = copy.deepcopy(template)
        result.update(record)
        # Validate serializability by round-tripping
        validated = json.loads(json.dumps(result))
        output.append(json.dumps(validated))
    return output


def aggregate_results(results: list[str]) -> dict:
    """Aggregate streamed JSON-line results into summary statistics."""
    parsed = [json.loads(r) for r in results]

    all_keys = []
    for record in parsed:
        for key in record:
            if key not in all_keys:
                all_keys.append(key)

    summary = {}
    for key in all_keys:
        values = [r.get(key) for r in parsed if key in r]
        summary[key] = {
            "count": len(values),
            "unique": len(set(str(v) for v in values)),
        }
    return summary
