import os
import csv
import tempfile
import exiftool
import shutil

class MetadataExtractor:
    def __init__(self, args, ptjsonlib):
        self.args = args
        self.ptjsonlib = ptjsonlib
        self.exif_executable = shutil.which("exiftool")
        if not self.exif_executable:
            self.ptjsonlib.end_error("ExifTool not found. install first via 'sudo apt install exiftool' command.", self.args.json)

    def get_metadata(self, response=None, path_to_local_file=None) -> dict:
        if response is not None:
            tmp = tempfile.NamedTemporaryFile()
            with open(tmp.name, 'wb') as f:
                f.write(response.content)
            with exiftool.ExifTool(executable=self.exif_executable) as exif_tool:
                result_dict = exif_tool.execute_json(tmp.name)[0]

        elif path_to_local_file:
            with exiftool.ExifTool(executable=self.exif_executable) as exif_tool:
                result_dict = exif_tool.execute_json(path_to_local_file)[0]

        blacklisted_keys = ["SourceFile", "ExifTool:ExifToolVersion", "File:FileName", "File:Directory", "File:FileSize", "File:FileModifyDate", "File:FileInodeChangeDate", "File:FilePermissions", "File:FileAccessDate", "File:FileType", "File:FileTypeExtension", "File:MIMEType"]
        result_dict = {k: v for k, v in result_dict.items() if k not in blacklisted_keys and v}
        file_identifier = response.url if response is not None else path_to_local_file
        result_dict.update({"SourceFile": file_identifier})

        """
        if self.args.output:
            self._write_metadata_to_csv(result_dict, file_identifier)
        """
        return result_dict

def write_metadata_to_csv(metadata_list, output_prefix):
    """
    Converts a list of metadata dictionaries to a CSV file.
    Ensures 'SourceFile' is the first column.
    """
    csv_path = f"{output_prefix}-metadata.csv"

    # Collect all unique keys across all dictionaries
    all_keys = set()
    for meta in metadata_list:
        all_keys.update(meta.keys())

    # Reorder keys: SourceFile first
    all_keys = ["SourceFile"] + [k for k in all_keys if k != "SourceFile"]

    # Write to CSV
    with open(csv_path, mode='w', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=all_keys, quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writeheader()
        for meta in metadata_list:
            row = {}
            for k in all_keys:
                value = meta.get(k, "")
                if isinstance(value, list):
                    value = "; ".join(str(v).replace(",", ";") for v in value)
                else:
                    value = str(value).replace(",", ";")
                row[k] = value
            writer.writerow(row)