import os

def extract_first_four_dash_lines(filepath):
    extracted = []
    dash_line_count = 0
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            extracted.append(line)
            if line.lstrip().startswith('—'):
                dash_line_count += 1
                if dash_line_count == 4:
                    break
    return extracted

def extract_last_five_lines(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    return lines[-5:]

def check_content_in_file(content, filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        full_text = f.read()
    return ''.join(content) in full_text

def process_directory(base_path):
    differences_found = False
    for dirpath, dirnames, filenames in os.walk(base_path):
        folder = os.path.basename(dirpath)
        f1 = f"hints2_{folder}"
        f2 = f"hints2_pre_gtk3_20_{folder}"
        if f1 in filenames and f2 in filenames:
            file1 = os.path.join(dirpath, f1)
            file2 = os.path.join(dirpath, f2)

            first_part = extract_first_four_dash_lines(file1)
            last_part = extract_last_five_lines(file1)

            issues = []

            if not check_content_in_file(first_part, file2):
                issues.append("Initial segment not found in " + f2)
            if not check_content_in_file(last_part, file2):
                issues.append("Final 5 lines not found in " + f2)

            if issues:
                differences_found = True
                print(f"[{folder}] Differences found:")
                for issue in issues:
                    print("  -", issue)
                print()
    if not differences_found:
        print("✅ No differences found in any folder.")

if __name__ == "__main__":
    base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../txts/hints"))
    process_directory(base_dir)
