#!/usr/bin/env python3
"""Convert i1Profiler PXF files to ArgyllCMS TI1 format."""

import sys
import xml.etree.ElementTree as ET
from datetime import datetime

NS = {"cc": "http://colorexchangeformat.com/CxF3-core"}


def parse_pxf(path):
    tree = ET.parse(path)
    root = tree.getroot()
    objects = root.findall(".//cc:Object", NS)
    patches = []
    for obj in objects:
        r = int(obj.find(".//cc:R", NS).text)
        g = int(obj.find(".//cc:G", NS).text)
        b = int(obj.find(".//cc:B", NS).text)
        patches.append((r, g, b))
    return patches


def patches_to_ti1(patches, output_path, target_name="from_pxf"):
    n = len(patches)
    now = datetime.now().strftime("%a %b %d %H:%M:%S %Y")

    lines = []
    lines.append("CTI1")
    lines.append("")
    lines.append(f'DESCRIPTOR "Argyll Calibration Target chart information 1"')
    lines.append(f'ORIGINATOR "pxf_to_ti1"')
    lines.append(f'CREATED "{now}"')
    lines.append(f'COLOR_REP "iRGB"')
    lines.append(f'TOTAL_INK_LIMIT "300.0"')
    lines.append(f'OFPS_PATCHES "{n}"')
    lines.append("")
    lines.append("NUMBER_OF_FIELDS 7")
    lines.append("BEGIN_DATA_FORMAT")
    lines.append("SAMPLE_ID RGB_R RGB_G RGB_B XYZ_X XYZ_Y XYZ_Z")
    lines.append("END_DATA_FORMAT")
    lines.append("")
    lines.append(f"NUMBER_OF_SETS {n}")
    lines.append("BEGIN_DATA")
    for i, (r, g, b) in enumerate(patches, 1):
        rf = r / 2.55
        gf = g / 2.55
        bf = b / 2.55
        lines.append(f"{i} {rf:.4f} {gf:.4f} {bf:.4f} 0.000000 0.000000 0.000000")
    lines.append("END_DATA")
    lines.append("")

    with open(output_path, "w") as f:
        f.write("\n".join(lines))
    print(f"Wrote {n} patches to {output_path}")


def main():
    if len(sys.argv) < 2:
        print("Usage: pxf_to_ti1.py input.pxf [output.ti1]")
        sys.exit(1)

    input_path = sys.argv[1]
    if len(sys.argv) > 2:
        output_path = sys.argv[2]
    else:
        output_path = input_path.rsplit(".", 1)[0] + ".ti1"

    patches = parse_pxf(input_path)
    print(f"Read {len(patches)} patches from {input_path}")
    patches_to_ti1(patches, output_path)


if __name__ == "__main__":
    main()
