#!/usr/bin/env python3
from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path


FIELDS = [
    "target",
    "source",
    "metric_name",
    "metric_value",
    "url",
    "captured_at",
    "status",
    "confidence",
    "notes",
    "screenshot_path",
]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Convert evidence.json to evidence.csv.")
    parser.add_argument("--json", required=True, help="Path to evidence.json")
    parser.add_argument("--csv", required=True, help="Path to output evidence.csv")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    json_path = Path(args.json)
    csv_path = Path(args.csv)
    csv_path.parent.mkdir(parents=True, exist_ok=True)

    payload = json.loads(json_path.read_text(encoding="utf-8"))
    rows = payload.get("evidence", [])

    with csv_path.open("w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore")
        writer.writeheader()
        for row in rows:
            writer.writerow({k: row.get(k) for k in FIELDS})

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

