#!/usr/bin/env python3
"""Ändert Bildmetadaten und ersetzt optional die Bilddatei."""

import argparse
from collections.abc import Sequence

from common import add_common_arguments, ask, ask_path, ask_with_default, client_from_args, run


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Bilddatei oder Bildmetadaten ändern")
    add_common_arguments(parser)
    parser.add_argument("--route-id", type=int)
    parser.add_argument("--poi-id", type=int)
    parser.add_argument("--picture-id", type=int)
    parser.add_argument("--file")
    return parser


def main(argv: Sequence[str] | None = None):
    args = build_parser().parse_args(argv)
    client = client_from_args(args)
    route_id = ask("Route-ID", args.route_id, required=True, cast=int)
    poi_id = ask("POI-ID", args.poi_id, required=True, cast=int)
    picture_id = ask("Bild-ID", args.picture_id, required=True, cast=int)
    path = f"/api/routes/{route_id}/pois/{poi_id}/pictures/{picture_id}"
    current = client.request("GET", f"{path}?metadata=true")
    fields = {
        "caption": ask_with_default("Bildbeschreibung", current.get("caption", "")),
        "sequence": ask_with_default("Reihenfolge", current.get("sequence", 0), int),
    }
    picture = ask_path("Neue Bilddatei (leer: unverändert)", args.file, required=False)
    if picture:
        return client.request("PUT", path, fields=fields, files={"picture": picture})
    return client.request("PUT", path, json_body=fields)


if __name__ == "__main__":
    run(main)
