  
import json
from pathlib import Path
from datetime import datetime
from typing import Iterable
import sys

from ..chunkers.schema import CodeChunk


def write_dataset_metadata(
    chunks: Iterable[CodeChunk],
    output_path: Path,
    dataset_name: str,
    dataset_version: str,
):
    chunks = list(chunks)

    metadata = {
        "dataset_name": dataset_name,
        "dataset_version": dataset_version,
        "created_at": datetime.utcnow().isoformat() + "Z",
        "chunking_strategy": "pure_ast + tree_sitter_spans",
        "languages": sorted({c.language for c in chunks}),
        "python_version": sys.version.split()[0],
        "total_files": len({c.file_path for c in chunks}),
        "total_chunks": len(chunks),
    }

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(
        json.dumps(metadata, indent=2),
        encoding="utf-8"
    )
