/-
Copyright (c) 2026 the Nonadditivity project contributors.
All rights reserved. See COPYRIGHT.md for licensing and attribution.
-/

import Nonadditivity.HaarPathProfiles
import Mathlib.Algebra.BigOperators.Group.Finset.Basic

/-! # Exact pairing count for orientation reversal -/
noncomputable section
namespace Nonadditivity.HaarPathInvolution
open scoped BigOperators
variable {α : Type*} [Fintype α] [DecidableEq α]

/-- The literal unordered pairs generated by an involution. -/
def pairs (f : α → α) : Finset (Finset α) := Finset.univ.image fun a => {a,f a}

omit [Fintype α] in
lemma pair_eq_of_mem {f : α → α} (hf : Function.Involutive f) {a b : α}
    (h : a ∈ ({b,f b} : Finset α)) : ({a,f a} : Finset α) = {b,f b} := by
  simp only [Finset.mem_insert,Finset.mem_singleton] at h
  rcases h with rfl | rfl
  · rfl
  · rw [hf]
    exact Finset.pair_comm _ _

/-- Distinct reversal orbits are disjoint. -/
theorem pairs_pairwiseDisjoint {f : α → α} (hf : Function.Involutive f) :
    ((pairs f : Finset (Finset α)) : Set (Finset α)).PairwiseDisjoint id := by
  intro s hs t ht hst
  obtain ⟨a,_,rfl⟩ := Finset.mem_image.mp hs
  obtain ⟨b,_,rfl⟩ := Finset.mem_image.mp ht
  apply Finset.disjoint_left.mpr
  intro c hc hc'
  apply hst
  exact (pair_eq_of_mem hf hc).symm.trans (pair_eq_of_mem hf hc')

theorem biUnion_pairs (f : α → α) : (pairs f).biUnion id = Finset.univ := by
  apply Finset.eq_univ_of_forall
  intro a
  apply Finset.mem_biUnion.mpr
  exact ⟨{a,f a},Finset.mem_image.mpr ⟨a,Finset.mem_univ _,rfl⟩,by simp⟩

/-- A fixed-point-free reversal pairs every object with exactly one distinct
opposite orientation; the number of pairs is exactly half the cardinality. -/
theorem twice_card_pairs {f : α → α} (hf : Function.Involutive f)
    (hfree : ∀ a, f a ≠ a) : 2*(pairs f).card = Fintype.card α := by
  have h := Finset.card_biUnion (pairs_pairwiseDisjoint hf)
  rw [biUnion_pairs,Finset.card_univ] at h
  have hc (s : Finset α) (hs : s ∈ pairs f) : s.card=2 := by
    obtain ⟨a,_,rfl⟩ := Finset.mem_image.mp hs
    simp [Ne.symm (hfree a)]
  simp only [id_eq] at h
  rw [Finset.sum_congr rfl hc] at h
  simpa [mul_comm] using h.symm

end Nonadditivity.HaarPathInvolution
