from __future__ import annotations

import argparse

from .core import generate_pca_html


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="citall",
        description="Create an interactive 3D PCA explorer from embeddings.",
    )
    parser.add_argument("--vectors", required=True, help="Path to .pt embedding file")
    parser.add_argument("--output", default="citall_plot.html", help="Output HTML path")
    parser.add_argument("--metadata", help="Path to .json or .jsonl metadata file")
    parser.add_argument("--metadata-key", help="Metadata key used to match embedding ids")
    parser.add_argument("--images-dir", help="Directory containing images named by id")
    parser.add_argument("--vector-key", help="Key for vectors when .pt contains a dict")
    parser.add_argument("--id-key", help="Key for ids when .pt contains a dict")
    parser.add_argument(
        "--strict-metadata",
        action="store_true",
        help="Fail if an embedding id has no metadata entry",
    )
    parser.add_argument(
        "--hover-fields",
        help="Comma-separated list of metadata fields for hover preview",
    )
    parser.add_argument(
        "--color-by",
        help="Metadata field used to split points into colored legend groups",
    )
    parser.add_argument(
        "--legend-title",
        help="Optional legend title override",
    )
    parser.add_argument("--title", default="citall: PCA 3D Explorer", help="Plot title")
    parser.add_argument("--point-size", type=int, default=5, help="Marker size")
    return parser


def main() -> None:
    parser = _build_parser()
    args = parser.parse_args()

    hover_fields = None
    if args.hover_fields:
        hover_fields = [x.strip() for x in args.hover_fields.split(",") if x.strip()]

    output = generate_pca_html(
        vectors_pt=args.vectors,
        output_html=args.output,
        metadata_path=args.metadata,
        metadata_key=args.metadata_key,
        images_dir=args.images_dir,
        vector_key=args.vector_key,
        id_key=args.id_key,
        strict_metadata=args.strict_metadata,
        title=args.title,
        hover_fields=hover_fields,
        point_size=args.point_size,
        color_by=args.color_by,
        legend_title=args.legend_title,
    )
    print(f"citall: wrote {output}")


if __name__ == "__main__":
    main()
