#!/usr/bin/env python3
import csv
import sys
import zipfile

if len(sys.argv) < 2:
    print("Usage: python3 check_odoo_version.py <dump.zip>")
    sys.exit(1)

zip_path = sys.argv[1]
base_version = None

with zipfile.ZipFile(zip_path, 'r') as z:
    # Assume there is only one .sql file in the zip
    sql_files = [f for f in z.namelist() if f.endswith('.sql')]
    if not sql_files:
        print("No .sql file found in the zip.")
        sys.exit(1)

    sql_file_name = sql_files[0]

    with z.open(sql_file_name, 'r') as f:
        # Decode bytes to string
        lines = (line.decode('utf-8') for line in f)

        # Skip lines until COPY command
        for line in lines:
            if line.startswith("COPY public.ir_module_module"):
                break

        # Read the COPY data until the terminator '\.'
        reader = csv.reader(lines, delimiter='\t', quotechar='"', escapechar='\\')
        for row in reader:
            if row == ['\\.']:  # End of COPY
                break
            if len(row) < 12:
                continue
            module_name = row[7].strip()  # 8th column = name
            if module_name == "base":
                base_version = row[11].strip()  # 12th column = latest_version
                break

if base_version:
    print(base_version.split(".")[0])
else:
    print("Base module not found in dump.")

