//! Family Tree Module for AiFastDb
//!
//! Provides specialized types and algorithms for family tree (genealogy) management:
//! - Family member management with gender and generation tracking
//! - Parent-child, spouse, and sibling relationship management
//! - Ancestor and descendant traversal
//! - Relationship calculation and Chinese kinship title derivation
//! - Family tree construction and statistics

use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use serde::{Deserialize, Serialize};

use crate::types::graph::{Entity, Relation, relation_types, gender};
use super::store_v2::SocialStoreV2;

// ============================================================================
// Types and Enums
// ============================================================================

/// Gender enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum Gender {
    Male,
    Female,
    #[default]
    Unknown,
}

impl Gender {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "male" | "m" | "男" => Gender::Male,
            "female" | "f" | "女" => Gender::Female,
            _ => Gender::Unknown,
        }
    }
    
    pub fn as_str(&self) -> &'static str {
        match self {
            Gender::Male => gender::MALE,
            Gender::Female => gender::FEMALE,
            Gender::Unknown => gender::UNKNOWN,
        }
    }
}

/// Family relationship type
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FamilyRelationType {
    // Direct blood relatives
    Father,
    Mother,
    Son,
    Daughter,
    Parent,     // Gender-neutral parent
    Child,      // Gender-neutral child
    
    // Spouse
    Spouse,
    Husband,
    Wife,
    ExSpouse,
    
    // Siblings
    Sibling,
    Brother,
    Sister,
    HalfSibling,
    
    // Grandparents/Grandchildren
    Grandfather,
    Grandmother,
    Grandparent,
    Grandson,
    Granddaughter,
    Grandchild,
    
    // Extended relatives
    Uncle,          // 叔伯舅
    Aunt,           // 姑姨
    Nephew,         // 侄子
    Niece,          // 侄女
    Cousin,         // 堂/表兄弟姐妹
    
    // In-laws
    FatherInLaw,
    MotherInLaw,
    SonInLaw,
    DaughterInLaw,
    BrotherInLaw,
    SisterInLaw,
}

impl FamilyRelationType {
    /// Convert to relation_type string for storage
    pub fn to_relation_type(&self) -> &'static str {
        match self {
            FamilyRelationType::Father | FamilyRelationType::Mother | FamilyRelationType::Parent => relation_types::PARENT_OF,
            FamilyRelationType::Son | FamilyRelationType::Daughter | FamilyRelationType::Child => relation_types::CHILD_OF,
            FamilyRelationType::Spouse | FamilyRelationType::Husband | FamilyRelationType::Wife => relation_types::SPOUSE_OF,
            FamilyRelationType::ExSpouse => relation_types::EX_SPOUSE_OF,
            FamilyRelationType::Sibling | FamilyRelationType::Brother | FamilyRelationType::Sister => relation_types::SIBLING_OF,
            FamilyRelationType::HalfSibling => relation_types::HALF_SIBLING_OF,
            FamilyRelationType::Grandfather | FamilyRelationType::Grandmother | FamilyRelationType::Grandparent => relation_types::GRANDPARENT_OF,
            FamilyRelationType::Grandson | FamilyRelationType::Granddaughter | FamilyRelationType::Grandchild => relation_types::GRANDCHILD_OF,
            _ => relation_types::FAMILY,
        }
    }
}

/// Family member input for creating new members
#[derive(Debug, Clone, Default)]
pub struct FamilyMemberInput {
    pub id: Option<String>,
    pub name: String,
    pub gender: Gender,
    pub birth_date: Option<String>,      // YYYY-MM-DD
    pub death_date: Option<String>,      // YYYY-MM-DD (optional)
    pub birth_order: Option<i32>,        // Birth order among siblings
    pub generation: Option<i32>,         // Generation number (0 = self, 1 = parent, -1 = child)
    pub properties: HashMap<String, serde_json::Value>,
}

/// Family relationship path between two people
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FamilyPath {
    pub from: Entity,
    pub to: Entity,
    pub path: Vec<FamilyPathStep>,
    pub relationship: String,            // Calculated relationship title
    pub generation_diff: i32,            // Generation difference (positive = elder, negative = younger)
    pub blood_distance: i32,             // Blood relationship distance
}

/// A step in the family path
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FamilyPathStep {
    pub person: Entity,
    pub relation_type: String,
    pub direction: PathDirection,
}

/// Direction in path traversal
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PathDirection {
    Up,      // Going to parent/elder
    Down,    // Going to child/younger
    Same,    // Same generation (sibling, spouse)
}

/// Family tree structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FamilyTree {
    pub root: Entity,
    pub members: Vec<Entity>,
    pub generations: HashMap<i32, Vec<Entity>>,
    pub total_generations: usize,
    pub relations: Vec<Relation>,
}

/// Family statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FamilyStats {
    pub total_members: usize,
    pub total_generations: usize,
    pub male_count: usize,
    pub female_count: usize,
    pub unknown_gender_count: usize,
    pub living_members: usize,
    pub deceased_members: usize,
    pub average_children: f64,
    pub earliest_birth: Option<String>,
    pub latest_birth: Option<String>,
}

// ============================================================================
// FamilyTreeMatcher Implementation
// ============================================================================

/// Family tree matcher for genealogy operations
pub struct FamilyTreeMatcher<'a> {
    store: &'a SocialStoreV2,
}

impl<'a> FamilyTreeMatcher<'a> {
    /// Create a new FamilyTreeMatcher
    pub fn new(store: &'a SocialStoreV2) -> Self {
        Self { store }
    }
    
    // ========================================================================
    // Core Relationship Management
    // ========================================================================
    
    /// Add parent-child relationship
    /// 
    /// Creates a directed relationship from parent to child.
    /// Automatically determines father/mother based on parent's gender.
    pub fn add_parent_child(&self, parent_id: &str, child_id: &str) -> Option<Relation> {
        let parent = self.store.get_person(parent_id)?;
        let _child = self.store.get_person(child_id)?;
        
        // Determine specific relation type based on parent's gender
        let parent_gender = self.get_person_gender(&parent);
        let relation_type = match parent_gender {
            Gender::Male => relation_types::FATHER_OF,
            Gender::Female => relation_types::MOTHER_OF,
            Gender::Unknown => relation_types::PARENT_OF,
        };
        
        let relation = Relation::new(parent_id, child_id, relation_type);
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Add spouse relationship (bidirectional)
    pub fn add_spouse(&self, person_a: &str, person_b: &str) -> Option<Relation> {
        let entity_a = self.store.get_person(person_a)?;
        let entity_b = self.store.get_person(person_b)?;
        
        // Determine specific relation type based on genders
        let gender_a = self.get_person_gender(&entity_a);
        let gender_b = self.get_person_gender(&entity_b);
        
        let relation_type = match (gender_a, gender_b) {
            (Gender::Male, Gender::Female) => relation_types::HUSBAND_OF,
            (Gender::Female, Gender::Male) => relation_types::WIFE_OF,
            _ => relation_types::SPOUSE_OF,
        };
        
        let relation = Relation::new(person_a, person_b, relation_type).bidirectional();
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Add sibling relationship (bidirectional)
    /// 
    /// If half_sibling is true, creates a half-sibling relationship.
    pub fn add_sibling(&self, person_a: &str, person_b: &str, half_sibling: bool) -> Option<Relation> {
        let entity_a = self.store.get_person(person_a)?;
        let _entity_b = self.store.get_person(person_b)?;
        
        let relation_type = if half_sibling {
            relation_types::HALF_SIBLING_OF
        } else {
            // Determine specific relation type based on person_a's gender
            let gender_a = self.get_person_gender(&entity_a);
            match gender_a {
                Gender::Male => relation_types::BROTHER_OF,
                Gender::Female => relation_types::SISTER_OF,
                Gender::Unknown => relation_types::SIBLING_OF,
            }
        };
        
        let relation = Relation::new(person_a, person_b, relation_type).bidirectional();
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Add step-parent to step-child relationship (继父母-继子女关系)
    /// 
    /// Used for remarriage families where one spouse brings children from previous marriage.
    pub fn add_step_parent_child(&self, step_parent_id: &str, step_child_id: &str) -> Option<Relation> {
        let step_parent = self.store.get_person(step_parent_id)?;
        let _step_child = self.store.get_person(step_child_id)?;
        
        let step_parent_gender = self.get_person_gender(&step_parent);
        let relation_type = match step_parent_gender {
            Gender::Male => relation_types::STEP_FATHER_OF,
            Gender::Female => relation_types::STEP_MOTHER_OF,
            Gender::Unknown => relation_types::STEP_PARENT_OF,
        };
        
        let relation = Relation::new(step_parent_id, step_child_id, relation_type);
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Add adoptive parent to adopted child relationship (养父母-养子女关系)
    pub fn add_adoptive_parent_child(&self, adoptive_parent_id: &str, adopted_child_id: &str) -> Option<Relation> {
        let adoptive_parent = self.store.get_person(adoptive_parent_id)?;
        let _adopted_child = self.store.get_person(adopted_child_id)?;
        
        let parent_gender = self.get_person_gender(&adoptive_parent);
        let relation_type = match parent_gender {
            Gender::Male => relation_types::ADOPTIVE_FATHER_OF,
            Gender::Female => relation_types::ADOPTIVE_MOTHER_OF,
            Gender::Unknown => relation_types::ADOPTIVE_PARENT_OF,
        };
        
        let relation = Relation::new(adoptive_parent_id, adopted_child_id, relation_type);
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Add ex-spouse relationship (前配偶关系)
    pub fn add_ex_spouse(&self, person_a: &str, person_b: &str) -> Option<Relation> {
        let _entity_a = self.store.get_person(person_a)?;
        let _entity_b = self.store.get_person(person_b)?;
        
        let relation = Relation::new(person_a, person_b, relation_types::EX_SPOUSE_OF).bidirectional();
        self.store.put_relation(relation.clone());
        Some(relation)
    }
    
    /// Remove family relationship between two people
    pub fn remove_family_relation(&self, person_a: &str, person_b: &str) -> bool {
        let mut removed = false;
        
        // Check outgoing relations from person_a
        for rel in self.store.outgoing_from(person_a) {
            if rel.target == person_b && is_family_relation(&rel.relation_type) {
                self.store.delete_relation(&rel.id);
                removed = true;
            }
        }
        
        // Check outgoing relations from person_b (for bidirectional)
        for rel in self.store.outgoing_from(person_b) {
            if rel.target == person_a && is_family_relation(&rel.relation_type) {
                self.store.delete_relation(&rel.id);
                removed = true;
            }
        }
        
        removed
    }
    
    // ========================================================================
    // Direct Family Queries
    // ========================================================================
    
    /// Get parents of a person
    pub fn get_parents(&self, person_id: &str) -> Vec<Entity> {
        let mut parents = Vec::new();
        
        // Find incoming parent_of/father_of/mother_of relations
        for rel in self.store.incoming_to(person_id) {
            if is_parent_relation(&rel.relation_type) {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    parents.push(parent);
                }
            }
        }
        
        parents
    }
    
    /// Get father of a person
    pub fn get_father(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::FATHER_OF {
                return self.store.get_person(&rel.source);
            }
            // Also check generic parent_of and filter by gender
            if rel.relation_type == relation_types::PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Male {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get mother of a person
    pub fn get_mother(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::MOTHER_OF {
                return self.store.get_person(&rel.source);
            }
            // Also check generic parent_of and filter by gender
            if rel.relation_type == relation_types::PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Female {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get children of a person
    pub fn get_children(&self, person_id: &str) -> Vec<Entity> {
        let mut children = Vec::new();
        
        // Find outgoing parent_of/father_of/mother_of relations
        for rel in self.store.outgoing_from(person_id) {
            if is_parent_relation(&rel.relation_type) {
                if let Some(child) = self.store.get_person(&rel.target) {
                    children.push(child);
                }
            }
        }
        
        // Sort by birth_order if available
        children.sort_by(|a, b| {
            let order_a = a.properties.get("birth_order")
                .and_then(|v| v.as_i64())
                .unwrap_or(i64::MAX);
            let order_b = b.properties.get("birth_order")
                .and_then(|v| v.as_i64())
                .unwrap_or(i64::MAX);
            order_a.cmp(&order_b)
        });
        
        children
    }
    
    /// Get sons of a person
    pub fn get_sons(&self, person_id: &str) -> Vec<Entity> {
        self.get_children(person_id)
            .into_iter()
            .filter(|c| self.get_person_gender(c) == Gender::Male)
            .collect()
    }
    
    /// Get daughters of a person
    pub fn get_daughters(&self, person_id: &str) -> Vec<Entity> {
        self.get_children(person_id)
            .into_iter()
            .filter(|c| self.get_person_gender(c) == Gender::Female)
            .collect()
    }
    
    /// Get spouse of a person
    pub fn get_spouse(&self, person_id: &str) -> Option<Entity> {
        // Check outgoing spouse relations
        for rel in self.store.outgoing_from(person_id) {
            if is_spouse_relation(&rel.relation_type) && rel.relation_type != relation_types::EX_SPOUSE_OF {
                return self.store.get_person(&rel.target);
            }
        }
        
        // Check incoming spouse relations (bidirectional)
        for rel in self.store.incoming_to(person_id) {
            if is_spouse_relation(&rel.relation_type) && rel.relation_type != relation_types::EX_SPOUSE_OF && rel.bidirectional {
                return self.store.get_person(&rel.source);
            }
        }
        
        None
    }
    
    /// Get all spouses (including ex-spouses)
    pub fn get_all_spouses(&self, person_id: &str) -> Vec<(Entity, bool)> {
        let mut spouses = Vec::new();
        let mut seen = HashSet::new();
        
        // Check outgoing
        for rel in self.store.outgoing_from(person_id) {
            if is_spouse_relation(&rel.relation_type) {
                if let Some(spouse) = self.store.get_person(&rel.target) {
                    if seen.insert(spouse.id.clone()) {
                        let is_ex = rel.relation_type == relation_types::EX_SPOUSE_OF;
                        spouses.push((spouse, is_ex));
                    }
                }
            }
        }
        
        // Check incoming (bidirectional)
        for rel in self.store.incoming_to(person_id) {
            if is_spouse_relation(&rel.relation_type) && rel.bidirectional {
                if let Some(spouse) = self.store.get_person(&rel.source) {
                    if seen.insert(spouse.id.clone()) {
                        let is_ex = rel.relation_type == relation_types::EX_SPOUSE_OF;
                        spouses.push((spouse, is_ex));
                    }
                }
            }
        }
        
        spouses
    }
    
    /// Get step-parents of a person (继父母)
    pub fn get_step_parents(&self, person_id: &str) -> Vec<Entity> {
        let mut step_parents = Vec::new();
        
        for rel in self.store.incoming_to(person_id) {
            if is_step_parent_relation(&rel.relation_type) {
                if let Some(step_parent) = self.store.get_person(&rel.source) {
                    step_parents.push(step_parent);
                }
            }
        }
        
        step_parents
    }
    
    /// Get step-father (继父)
    pub fn get_step_father(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::STEP_FATHER_OF {
                return self.store.get_person(&rel.source);
            }
            if rel.relation_type == relation_types::STEP_PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Male {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get step-mother (继母)
    pub fn get_step_mother(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::STEP_MOTHER_OF {
                return self.store.get_person(&rel.source);
            }
            if rel.relation_type == relation_types::STEP_PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Female {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get step-children (继子女)
    pub fn get_step_children(&self, person_id: &str) -> Vec<Entity> {
        let mut step_children = Vec::new();
        
        for rel in self.store.outgoing_from(person_id) {
            if is_step_parent_relation(&rel.relation_type) {
                if let Some(child) = self.store.get_person(&rel.target) {
                    step_children.push(child);
                }
            }
        }
        
        step_children
    }
    
    /// Get adoptive parents (养父母)
    pub fn get_adoptive_parents(&self, person_id: &str) -> Vec<Entity> {
        let mut adoptive_parents = Vec::new();
        
        for rel in self.store.incoming_to(person_id) {
            if is_adoptive_parent_relation(&rel.relation_type) {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    adoptive_parents.push(parent);
                }
            }
        }
        
        adoptive_parents
    }
    
    /// Get adoptive father (养父)
    pub fn get_adoptive_father(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::ADOPTIVE_FATHER_OF {
                return self.store.get_person(&rel.source);
            }
            if rel.relation_type == relation_types::ADOPTIVE_PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Male {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get adoptive mother (养母)
    pub fn get_adoptive_mother(&self, person_id: &str) -> Option<Entity> {
        for rel in self.store.incoming_to(person_id) {
            if rel.relation_type == relation_types::ADOPTIVE_MOTHER_OF {
                return self.store.get_person(&rel.source);
            }
            if rel.relation_type == relation_types::ADOPTIVE_PARENT_OF {
                if let Some(parent) = self.store.get_person(&rel.source) {
                    if self.get_person_gender(&parent) == Gender::Female {
                        return Some(parent);
                    }
                }
            }
        }
        None
    }
    
    /// Get adopted children (养子女)
    pub fn get_adopted_children(&self, person_id: &str) -> Vec<Entity> {
        let mut adopted_children = Vec::new();
        
        for rel in self.store.outgoing_from(person_id) {
            if is_adoptive_parent_relation(&rel.relation_type) {
                if let Some(child) = self.store.get_person(&rel.target) {
                    adopted_children.push(child);
                }
            }
        }
        
        adopted_children
    }
    
    /// Get all parents (biological + step + adoptive) - 所有父母（亲生+继+养）
    pub fn get_all_parents(&self, person_id: &str) -> Vec<(Entity, String)> {
        let mut parents = Vec::new();
        
        // Biological parents
        for parent in self.get_parents(person_id) {
            parents.push((parent, "biological".to_string()));
        }
        
        // Step parents
        for parent in self.get_step_parents(person_id) {
            parents.push((parent, "step".to_string()));
        }
        
        // Adoptive parents
        for parent in self.get_adoptive_parents(person_id) {
            parents.push((parent, "adoptive".to_string()));
        }
        
        parents
    }
    
    /// Get all children (biological + step + adopted) - 所有子女（亲生+继+养）
    pub fn get_all_children(&self, person_id: &str) -> Vec<(Entity, String)> {
        let mut children = Vec::new();
        
        // Biological children
        for child in self.get_children(person_id) {
            children.push((child, "biological".to_string()));
        }
        
        // Step children
        for child in self.get_step_children(person_id) {
            children.push((child, "step".to_string()));
        }
        
        // Adopted children
        for child in self.get_adopted_children(person_id) {
            children.push((child, "adopted".to_string()));
        }
        
        children
    }
    
    /// Get siblings of a person
    pub fn get_siblings(&self, person_id: &str) -> Vec<Entity> {
        let mut siblings = Vec::new();
        let mut seen = HashSet::new();
        seen.insert(person_id.to_string());
        
        // Method 1: Direct sibling relations
        for rel in self.store.outgoing_from(person_id) {
            if is_sibling_relation(&rel.relation_type) {
                if let Some(sibling) = self.store.get_person(&rel.target) {
                    if seen.insert(sibling.id.clone()) {
                        siblings.push(sibling);
                    }
                }
            }
        }
        for rel in self.store.incoming_to(person_id) {
            if is_sibling_relation(&rel.relation_type) {
                if let Some(sibling) = self.store.get_person(&rel.source) {
                    if seen.insert(sibling.id.clone()) {
                        siblings.push(sibling);
                    }
                }
            }
        }
        
        // Method 2: Infer from shared parents
        let parents = self.get_parents(person_id);
        for parent in parents {
            for child in self.get_children(&parent.id) {
                if seen.insert(child.id.clone()) {
                    siblings.push(child);
                }
            }
        }
        
        // Sort by birth_order if available
        siblings.sort_by(|a, b| {
            let order_a = a.properties.get("birth_order")
                .and_then(|v| v.as_i64())
                .unwrap_or(i64::MAX);
            let order_b = b.properties.get("birth_order")
                .and_then(|v| v.as_i64())
                .unwrap_or(i64::MAX);
            order_a.cmp(&order_b)
        });
        
        siblings
    }
    
    /// Get brothers of a person
    pub fn get_brothers(&self, person_id: &str) -> Vec<Entity> {
        self.get_siblings(person_id)
            .into_iter()
            .filter(|s| self.get_person_gender(s) == Gender::Male)
            .collect()
    }
    
    /// Get sisters of a person
    pub fn get_sisters(&self, person_id: &str) -> Vec<Entity> {
        self.get_siblings(person_id)
            .into_iter()
            .filter(|s| self.get_person_gender(s) == Gender::Female)
            .collect()
    }
    
    // ========================================================================
    // Extended Family Queries
    // ========================================================================
    
    /// Get all ancestors (traversing upward)
    pub fn get_ancestors(&self, person_id: &str, max_generations: usize) -> Vec<Entity> {
        let mut ancestors = Vec::new();
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        
        visited.insert(person_id.to_string());
        queue.push_back((person_id.to_string(), 0usize));
        
        while let Some((current_id, gen)) = queue.pop_front() {
            if gen >= max_generations {
                continue;
            }
            
            for parent in self.get_parents(&current_id) {
                if visited.insert(parent.id.clone()) {
                    ancestors.push(parent.clone());
                    queue.push_back((parent.id.clone(), gen + 1));
                }
            }
        }
        
        ancestors
    }
    
    /// Get all descendants (traversing downward)
    pub fn get_descendants(&self, person_id: &str, max_generations: usize) -> Vec<Entity> {
        let mut descendants = Vec::new();
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        
        visited.insert(person_id.to_string());
        queue.push_back((person_id.to_string(), 0usize));
        
        while let Some((current_id, gen)) = queue.pop_front() {
            if gen >= max_generations {
                continue;
            }
            
            for child in self.get_children(&current_id) {
                if visited.insert(child.id.clone()) {
                    descendants.push(child.clone());
                    queue.push_back((child.id.clone(), gen + 1));
                }
            }
        }
        
        descendants
    }
    
    /// Get grandparents
    pub fn get_grandparents(&self, person_id: &str) -> Vec<Entity> {
        let mut grandparents = Vec::new();
        let mut seen = HashSet::new();
        
        for parent in self.get_parents(person_id) {
            for grandparent in self.get_parents(&parent.id) {
                if seen.insert(grandparent.id.clone()) {
                    grandparents.push(grandparent);
                }
            }
        }
        
        grandparents
    }
    
    /// Get paternal grandfather (爷爷)
    pub fn get_paternal_grandfather(&self, person_id: &str) -> Option<Entity> {
        let father = self.get_father(person_id)?;
        self.get_father(&father.id)
    }
    
    /// Get paternal grandmother (奶奶)
    pub fn get_paternal_grandmother(&self, person_id: &str) -> Option<Entity> {
        let father = self.get_father(person_id)?;
        self.get_mother(&father.id)
    }
    
    /// Get maternal grandfather (外公/姥爷)
    pub fn get_maternal_grandfather(&self, person_id: &str) -> Option<Entity> {
        let mother = self.get_mother(person_id)?;
        self.get_father(&mother.id)
    }
    
    /// Get maternal grandmother (外婆/姥姥)
    pub fn get_maternal_grandmother(&self, person_id: &str) -> Option<Entity> {
        let mother = self.get_mother(person_id)?;
        self.get_mother(&mother.id)
    }
    
    /// Get grandchildren
    pub fn get_grandchildren(&self, person_id: &str) -> Vec<Entity> {
        let mut grandchildren = Vec::new();
        let mut seen = HashSet::new();
        
        for child in self.get_children(person_id) {
            for grandchild in self.get_children(&child.id) {
                if seen.insert(grandchild.id.clone()) {
                    grandchildren.push(grandchild);
                }
            }
        }
        
        grandchildren
    }
    
    /// Get uncles and aunts (叔伯姑姨舅)
    pub fn get_uncles_aunts(&self, person_id: &str) -> Vec<Entity> {
        let mut result = Vec::new();
        let mut seen = HashSet::new();
        
        for parent in self.get_parents(person_id) {
            for sibling in self.get_siblings(&parent.id) {
                if seen.insert(sibling.id.clone()) {
                    result.push(sibling);
                }
            }
        }
        
        result
    }
    
    /// Get paternal uncles (叔叔/伯伯)
    pub fn get_paternal_uncles(&self, person_id: &str) -> Vec<Entity> {
        if let Some(father) = self.get_father(person_id) {
            self.get_brothers(&father.id)
        } else {
            Vec::new()
        }
    }
    
    /// Get paternal aunts (姑姑)
    pub fn get_paternal_aunts(&self, person_id: &str) -> Vec<Entity> {
        if let Some(father) = self.get_father(person_id) {
            self.get_sisters(&father.id)
        } else {
            Vec::new()
        }
    }
    
    /// Get maternal uncles (舅舅)
    pub fn get_maternal_uncles(&self, person_id: &str) -> Vec<Entity> {
        if let Some(mother) = self.get_mother(person_id) {
            self.get_brothers(&mother.id)
        } else {
            Vec::new()
        }
    }
    
    /// Get maternal aunts (姨妈)
    pub fn get_maternal_aunts(&self, person_id: &str) -> Vec<Entity> {
        if let Some(mother) = self.get_mother(person_id) {
            self.get_sisters(&mother.id)
        } else {
            Vec::new()
        }
    }
    
    /// Get nephews and nieces (侄子/侄女/外甥/外甥女)
    pub fn get_nephews_nieces(&self, person_id: &str) -> Vec<Entity> {
        let mut result = Vec::new();
        let mut seen = HashSet::new();
        
        for sibling in self.get_siblings(person_id) {
            for child in self.get_children(&sibling.id) {
                if seen.insert(child.id.clone()) {
                    result.push(child);
                }
            }
        }
        
        result
    }
    
    /// Get cousins (堂/表兄弟姐妹)
    pub fn get_cousins(&self, person_id: &str) -> Vec<Entity> {
        let mut cousins = Vec::new();
        let mut seen = HashSet::new();
        seen.insert(person_id.to_string());
        
        // Add self's siblings to seen to exclude them
        for sibling in self.get_siblings(person_id) {
            seen.insert(sibling.id.clone());
        }
        
        for uncle_aunt in self.get_uncles_aunts(person_id) {
            for child in self.get_children(&uncle_aunt.id) {
                if seen.insert(child.id.clone()) {
                    cousins.push(child);
                }
            }
        }
        
        cousins
    }
    
    /// Get paternal cousins (堂兄弟姐妹)
    pub fn get_paternal_cousins(&self, person_id: &str) -> Vec<Entity> {
        let mut cousins = Vec::new();
        let mut seen = HashSet::new();
        
        // Get father's siblings' children
        if let Some(father) = self.get_father(person_id) {
            for sibling in self.get_siblings(&father.id) {
                for child in self.get_children(&sibling.id) {
                    if seen.insert(child.id.clone()) {
                        cousins.push(child);
                    }
                }
            }
        }
        
        cousins
    }
    
    /// Get maternal cousins (表兄弟姐妹)
    pub fn get_maternal_cousins(&self, person_id: &str) -> Vec<Entity> {
        let mut cousins = Vec::new();
        let mut seen = HashSet::new();
        
        // Get mother's siblings' children
        if let Some(mother) = self.get_mother(person_id) {
            for sibling in self.get_siblings(&mother.id) {
                for child in self.get_children(&sibling.id) {
                    if seen.insert(child.id.clone()) {
                        cousins.push(child);
                    }
                }
            }
        }
        
        cousins
    }
    
    // ========================================================================
    // In-law Queries
    // ========================================================================
    
    /// Get father-in-law (公公/岳父)
    pub fn get_father_in_law(&self, person_id: &str) -> Option<Entity> {
        let spouse = self.get_spouse(person_id)?;
        self.get_father(&spouse.id)
    }
    
    /// Get mother-in-law (婆婆/岳母)
    pub fn get_mother_in_law(&self, person_id: &str) -> Option<Entity> {
        let spouse = self.get_spouse(person_id)?;
        self.get_mother(&spouse.id)
    }
    
    /// Get siblings-in-law (大伯/小叔/大姑/小姑/大舅/小舅等)
    pub fn get_siblings_in_law(&self, person_id: &str) -> Vec<Entity> {
        let mut result = Vec::new();
        let mut seen = HashSet::new();
        
        // Spouse's siblings
        if let Some(spouse) = self.get_spouse(person_id) {
            for sibling in self.get_siblings(&spouse.id) {
                if seen.insert(sibling.id.clone()) {
                    result.push(sibling);
                }
            }
        }
        
        // Siblings' spouses
        for sibling in self.get_siblings(person_id) {
            if let Some(spouse) = self.get_spouse(&sibling.id) {
                if seen.insert(spouse.id.clone()) {
                    result.push(spouse);
                }
            }
        }
        
        result
    }
    
    /// Get children-in-law (儿媳/女婿)
    pub fn get_children_in_law(&self, person_id: &str) -> Vec<Entity> {
        let mut result = Vec::new();
        
        for child in self.get_children(person_id) {
            if let Some(spouse) = self.get_spouse(&child.id) {
                result.push(spouse);
            }
        }
        
        result
    }
    
    // ========================================================================
    // Relationship Calculation
    // ========================================================================
    
    /// Calculate the family relationship between two people
    pub fn calculate_relationship(&self, from_id: &str, to_id: &str) -> Option<FamilyPath> {
        let from = self.store.get_person(from_id)?;
        let to = self.store.get_person(to_id)?;
        
        if from_id == to_id {
            return Some(FamilyPath {
                from: from.clone(),
                to: to.clone(),
                path: vec![],
                relationship: "自己".to_string(),
                generation_diff: 0,
                blood_distance: 0,
            });
        }
        
        // BFS to find shortest path
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        let mut parent_map: HashMap<String, (String, String, PathDirection)> = HashMap::new();
        
        visited.insert(from_id.to_string());
        queue.push_back(from_id.to_string());
        
        while let Some(current) = queue.pop_front() {
            if current == to_id {
                // Reconstruct path
                let mut path = Vec::new();
                let mut current_id = to_id.to_string();
                
                while let Some((prev_id, rel_type, direction)) = parent_map.get(&current_id) {
                    if let Some(person) = self.store.get_person(&current_id) {
                        path.push(FamilyPathStep {
                            person,
                            relation_type: rel_type.clone(),
                            direction: *direction,
                        });
                    }
                    current_id = prev_id.clone();
                }
                
                path.reverse();
                
                let (gen_diff, blood_dist) = self.calculate_path_metrics(&path);
                let relationship = self.derive_relationship_title(from_id, to_id, &path);
                
                return Some(FamilyPath {
                    from,
                    to,
                    path,
                    relationship,
                    generation_diff: gen_diff,
                    blood_distance: blood_dist,
                });
            }
            
            // Explore neighbors
            // Parents (going up)
            for parent in self.get_parents(&current) {
                if visited.insert(parent.id.clone()) {
                    let rel_type = if self.get_person_gender(&parent) == Gender::Male {
                        relation_types::FATHER_OF
                    } else {
                        relation_types::MOTHER_OF
                    };
                    parent_map.insert(parent.id.clone(), (current.clone(), rel_type.to_string(), PathDirection::Up));
                    queue.push_back(parent.id.clone());
                }
            }
            
            // Children (going down)
            for child in self.get_children(&current) {
                if visited.insert(child.id.clone()) {
                    parent_map.insert(child.id.clone(), (current.clone(), relation_types::CHILD_OF.to_string(), PathDirection::Down));
                    queue.push_back(child.id.clone());
                }
            }
            
            // Spouse (same level)
            if let Some(spouse) = self.get_spouse(&current) {
                if visited.insert(spouse.id.clone()) {
                    parent_map.insert(spouse.id.clone(), (current.clone(), relation_types::SPOUSE_OF.to_string(), PathDirection::Same));
                    queue.push_back(spouse.id.clone());
                }
            }
            
            // Siblings (same level)
            for sibling in self.get_siblings(&current) {
                if visited.insert(sibling.id.clone()) {
                    parent_map.insert(sibling.id.clone(), (current.clone(), relation_types::SIBLING_OF.to_string(), PathDirection::Same));
                    queue.push_back(sibling.id.clone());
                }
            }
        }
        
        None // No relationship found
    }
    
    /// Calculate generation difference and blood distance from path
    fn calculate_path_metrics(&self, path: &[FamilyPathStep]) -> (i32, i32) {
        let mut gen_diff = 0i32;
        let mut blood_dist = 0i32;
        
        for step in path {
            match step.direction {
                PathDirection::Up => {
                    gen_diff += 1;
                    blood_dist += 1;
                }
                PathDirection::Down => {
                    gen_diff -= 1;
                    blood_dist += 1;
                }
                PathDirection::Same => {
                    if step.relation_type == relation_types::SIBLING_OF 
                        || step.relation_type == relation_types::BROTHER_OF
                        || step.relation_type == relation_types::SISTER_OF {
                        blood_dist += 1;
                    }
                    // Spouse doesn't add blood distance
                }
            }
        }
        
        (gen_diff, blood_dist)
    }
    
    /// Derive Chinese relationship title from path
    fn derive_relationship_title(&self, from_id: &str, to_id: &str, path: &[FamilyPathStep]) -> String {
        if path.is_empty() {
            return "自己".to_string();
        }
        
        let from_gender = self.store.get_person(from_id)
            .map(|p| self.get_person_gender(&p))
            .unwrap_or(Gender::Unknown);
        
        let to_gender = self.store.get_person(to_id)
            .map(|p| self.get_person_gender(&p))
            .unwrap_or(Gender::Unknown);
        
        // Build path description
        let mut path_desc: Vec<(&str, PathDirection)> = Vec::new();
        for step in path {
            path_desc.push((step.relation_type.as_str(), step.direction));
        }
        
        // Match common patterns
        derive_chinese_kinship_title(&path_desc, from_gender, to_gender)
    }
    
    /// Get relationship title between two people
    pub fn get_relationship_title(&self, from_id: &str, to_id: &str) -> Option<String> {
        self.calculate_relationship(from_id, to_id)
            .map(|path| path.relationship)
    }
    
    /// Find common ancestor of two people
    pub fn find_common_ancestor(&self, person_a: &str, person_b: &str) -> Option<Entity> {
        let ancestors_a: HashSet<String> = self.get_ancestors(person_a, 10)
            .into_iter()
            .map(|e| e.id)
            .collect();
        
        // BFS from person_b to find first common ancestor
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        
        visited.insert(person_b.to_string());
        queue.push_back(person_b.to_string());
        
        while let Some(current) = queue.pop_front() {
            if ancestors_a.contains(&current) {
                return self.store.get_person(&current);
            }
            
            for parent in self.get_parents(&current) {
                if visited.insert(parent.id.clone()) {
                    queue.push_back(parent.id.clone());
                }
            }
        }
        
        None
    }
    
    /// Calculate blood distance between two people
    pub fn calculate_blood_distance(&self, person_a: &str, person_b: &str) -> Option<i32> {
        self.calculate_relationship(person_a, person_b)
            .map(|path| path.blood_distance)
    }
    
    /// Check if two people are direct blood relatives
    pub fn is_direct_blood_relative(&self, person_a: &str, person_b: &str) -> bool {
        // Check if one is ancestor/descendant of the other
        let ancestors_a: HashSet<String> = self.get_ancestors(person_a, 10)
            .into_iter()
            .map(|e| e.id)
            .collect();
        
        if ancestors_a.contains(person_b) {
            return true;
        }
        
        let descendants_a: HashSet<String> = self.get_descendants(person_a, 10)
            .into_iter()
            .map(|e| e.id)
            .collect();
        
        descendants_a.contains(person_b)
    }
    
    // ========================================================================
    // Family Tree Construction
    // ========================================================================
    
    /// Build family tree centered on a person
    pub fn build_family_tree(
        &self,
        person_id: &str,
        generations_up: usize,
        generations_down: usize,
    ) -> Option<FamilyTree> {
        let root = self.store.get_person(person_id)?;
        
        let mut members = Vec::new();
        let mut generations: HashMap<i32, Vec<Entity>> = HashMap::new();
        let mut relations = Vec::new();
        let mut visited = HashSet::new();
        
        // BFS to collect all family members
        let mut queue = VecDeque::new();
        queue.push_back((person_id.to_string(), 0i32)); // (person_id, generation relative to root)
        visited.insert(person_id.to_string());
        
        while let Some((current_id, gen)) = queue.pop_front() {
            if let Some(person) = self.store.get_person(&current_id) {
                members.push(person.clone());
                generations.entry(gen).or_insert_with(Vec::new).push(person);
            }
            
            // Go up (parents)
            if gen < generations_up as i32 {
                for parent in self.get_parents(&current_id) {
                    if visited.insert(parent.id.clone()) {
                        queue.push_back((parent.id.clone(), gen + 1));
                    }
                    // Collect parent relation
                    for rel in self.store.incoming_to(&current_id) {
                        if is_parent_relation(&rel.relation_type) && rel.source == parent.id {
                            relations.push(rel);
                        }
                    }
                }
            }
            
            // Go down (children)
            if (-gen) < generations_down as i32 {
                for child in self.get_children(&current_id) {
                    if visited.insert(child.id.clone()) {
                        queue.push_back((child.id.clone(), gen - 1));
                    }
                    // Collect child relation
                    for rel in self.store.outgoing_from(&current_id) {
                        if is_parent_relation(&rel.relation_type) && rel.target == child.id {
                            relations.push(rel);
                        }
                    }
                }
            }
            
            // Same generation (spouse, siblings)
            if let Some(spouse) = self.get_spouse(&current_id) {
                if visited.insert(spouse.id.clone()) {
                    queue.push_back((spouse.id.clone(), gen));
                }
            }
        }
        
        let total_generations = generations.len();
        
        Some(FamilyTree {
            root,
            members,
            generations,
            total_generations,
            relations,
        })
    }
    
    /// Get generation number of a person relative to a root
    pub fn get_generation(&self, person_id: &str, root_id: &str) -> Option<i32> {
        self.calculate_relationship(root_id, person_id)
            .map(|path| -path.generation_diff) // Negate because we calculate from root to person
    }
    
    /// Get all people in the same generation as a person
    pub fn get_same_generation(&self, person_id: &str) -> Vec<Entity> {
        let mut result = Vec::new();
        let mut seen = HashSet::new();
        seen.insert(person_id.to_string());
        
        // Siblings
        for sibling in self.get_siblings(person_id) {
            if seen.insert(sibling.id.clone()) {
                result.push(sibling);
            }
        }
        
        // Cousins
        for cousin in self.get_cousins(person_id) {
            if seen.insert(cousin.id.clone()) {
                result.push(cousin);
            }
        }
        
        // Spouse
        if let Some(spouse) = self.get_spouse(person_id) {
            if seen.insert(spouse.id.clone()) {
                result.push(spouse);
            }
        }
        
        result
    }
    
    // ========================================================================
    // Lineage Queries (血统查询)
    // ========================================================================
    
    /// Get paternal lineage (父系血统)
    /// 
    /// Traces the paternal line: father -> grandfather -> great-grandfather -> ...
    /// Returns ancestors in order from closest (father) to farthest.
    pub fn get_paternal_lineage(&self, person_id: &str, max_generations: usize) -> Vec<Entity> {
        let mut lineage = Vec::new();
        let mut current_id = person_id.to_string();
        
        for _ in 0..max_generations {
            if let Some(father) = self.get_father(&current_id) {
                lineage.push(father.clone());
                current_id = father.id;
            } else {
                break;
            }
        }
        
        lineage
    }
    
    /// Get maternal lineage (母系血统)
    /// 
    /// Traces the maternal line: mother -> grandmother -> great-grandmother -> ...
    /// Returns ancestors in order from closest (mother) to farthest.
    pub fn get_maternal_lineage(&self, person_id: &str, max_generations: usize) -> Vec<Entity> {
        let mut lineage = Vec::new();
        let mut current_id = person_id.to_string();
        
        for _ in 0..max_generations {
            if let Some(mother) = self.get_mother(&current_id) {
                lineage.push(mother.clone());
                current_id = mother.id;
            } else {
                break;
            }
        }
        
        lineage
    }
    
    /// Get same surname relatives (同姓族人)
    /// 
    /// Finds all relatives who share the same family_name property.
    /// Searches through the family tree starting from the person.
    pub fn get_same_surname_relatives(&self, person_id: &str) -> Vec<Entity> {
        let person = match self.store.get_person(person_id) {
            Some(p) => p,
            None => return Vec::new(),
        };
        
        // Get the person's family_name
        let family_name = match person.properties.get("family_name").and_then(|v| v.as_str()) {
            Some(name) => name.to_string(),
            None => return Vec::new(),
        };
        
        let mut result = Vec::new();
        let mut visited = HashSet::new();
        visited.insert(person_id.to_string());
        
        // Get all ancestors and their descendants with the same surname
        let ancestors = self.get_ancestors(person_id, 10);
        
        for ancestor in ancestors {
            // Check if ancestor has same surname
            let ancestor_surname = ancestor.properties.get("family_name")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            
            if ancestor_surname == family_name {
                if visited.insert(ancestor.id.clone()) {
                    result.push(ancestor.clone());
                }
                
                // Get all descendants of this ancestor
                for descendant in self.get_descendants(&ancestor.id, 10) {
                    let desc_surname = descendant.properties.get("family_name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    
                    if desc_surname == family_name && visited.insert(descendant.id.clone()) {
                        result.push(descendant);
                    }
                }
            }
        }
        
        // Also check siblings and their descendants
        for sibling in self.get_siblings(person_id) {
            let sibling_surname = sibling.properties.get("family_name")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            
            if sibling_surname == family_name && visited.insert(sibling.id.clone()) {
                result.push(sibling.clone());
                
                for descendant in self.get_descendants(&sibling.id, 10) {
                    let desc_surname = descendant.properties.get("family_name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    
                    if desc_surname == family_name && visited.insert(descendant.id.clone()) {
                        result.push(descendant);
                    }
                }
            }
        }
        
        // Check own descendants
        for descendant in self.get_descendants(person_id, 10) {
            let desc_surname = descendant.properties.get("family_name")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            
            if desc_surname == family_name && visited.insert(descendant.id.clone()) {
                result.push(descendant);
            }
        }
        
        result
    }
    
    /// Get paternal clan members (父系宗族成员)
    /// 
    /// Gets all members connected through paternal lineage:
    /// - Paternal ancestors
    /// - Paternal uncles/aunts and their descendants
    /// - Siblings and their descendants (through father)
    pub fn get_paternal_clan(&self, person_id: &str, max_generations: usize) -> Vec<Entity> {
        let mut result = Vec::new();
        let mut visited = HashSet::new();
        visited.insert(person_id.to_string());
        
        // Find the earliest paternal ancestor (clan founder)
        let paternal_lineage = self.get_paternal_lineage(person_id, max_generations);
        
        let founder_id = if let Some(founder) = paternal_lineage.last() {
            founder.id.clone()
        } else if let Some(father) = self.get_father(person_id) {
            father.id.clone()
        } else {
            // No father found, return just siblings' descendants
            for sibling in self.get_siblings(person_id) {
                if visited.insert(sibling.id.clone()) {
                    result.push(sibling.clone());
                    for desc in self.get_descendants(&sibling.id, max_generations) {
                        if visited.insert(desc.id.clone()) {
                            result.push(desc);
                        }
                    }
                }
            }
            return result;
        };
        
        // Get all descendants of the founder
        if visited.insert(founder_id.clone()) {
            if let Some(founder) = self.store.get_person(&founder_id) {
                result.push(founder);
            }
        }
        
        for descendant in self.get_descendants(&founder_id, max_generations * 2) {
            if visited.insert(descendant.id.clone()) {
                result.push(descendant);
            }
        }
        
        result
    }
    
    // ========================================================================
    // Statistics
    // ========================================================================
    
    /// Get family statistics for a family tree
    pub fn get_family_stats(&self, root_id: &str) -> Option<FamilyStats> {
        let tree = self.build_family_tree(root_id, 5, 5)?;
        
        let mut male_count = 0;
        let mut female_count = 0;
        let mut unknown_gender_count = 0;
        let mut living_members = 0;
        let mut deceased_members = 0;
        let mut total_children = 0;
        let mut parents_count = 0;
        let mut earliest_birth: Option<String> = None;
        let mut latest_birth: Option<String> = None;
        
        for member in &tree.members {
            // Count by gender
            match self.get_person_gender(member) {
                Gender::Male => male_count += 1,
                Gender::Female => female_count += 1,
                Gender::Unknown => unknown_gender_count += 1,
            }
            
            // Check if living or deceased
            if member.properties.contains_key("death_date") {
                deceased_members += 1;
            } else {
                living_members += 1;
            }
            
            // Birth date statistics
            if let Some(birth_date) = member.properties.get("birth_date").and_then(|v| v.as_str()) {
                if earliest_birth.as_ref().map_or(true, |e| birth_date < e.as_str()) {
                    earliest_birth = Some(birth_date.to_string());
                }
                if latest_birth.as_ref().map_or(true, |l| birth_date > l.as_str()) {
                    latest_birth = Some(birth_date.to_string());
                }
            }
            
            // Count children for average calculation
            let children = self.get_children(&member.id);
            if !children.is_empty() {
                total_children += children.len();
                parents_count += 1;
            }
        }
        
        let average_children = if parents_count > 0 {
            total_children as f64 / parents_count as f64
        } else {
            0.0
        };
        
        Some(FamilyStats {
            total_members: tree.members.len(),
            total_generations: tree.total_generations,
            male_count,
            female_count,
            unknown_gender_count,
            living_members,
            deceased_members,
            average_children,
            earliest_birth,
            latest_birth,
        })
    }
    
    // ========================================================================
    // Helper Methods
    // ========================================================================
    
    /// Get gender of a person from their properties
    pub fn get_person_gender(&self, person: &Entity) -> Gender {
        person.properties.get("gender")
            .and_then(|v| v.as_str())
            .map(Gender::from_str)
            .unwrap_or(Gender::Unknown)
    }
    
    /// Set gender for a person
    pub fn set_person_gender(&self, person_id: &str, gender: Gender) -> bool {
        if let Some(mut person) = self.store.get_person(person_id) {
            person.properties.insert("gender".to_string(), serde_json::json!(gender.as_str()));
            person.updated_at = chrono_now();
            self.store.put_entity(person);
            true
        } else {
            false
        }
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

fn chrono_now() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64
}

fn is_family_relation(rel_type: &str) -> bool {
    is_parent_relation(rel_type) 
        || is_spouse_relation(rel_type) 
        || is_sibling_relation(rel_type)
        || is_step_parent_relation(rel_type)
        || is_adoptive_parent_relation(rel_type)
        || rel_type == relation_types::GRANDPARENT_OF
        || rel_type == relation_types::GRANDCHILD_OF
        || rel_type == relation_types::FAMILY
}

fn is_parent_relation(rel_type: &str) -> bool {
    matches!(rel_type,
        relation_types::PARENT_OF |
        relation_types::FATHER_OF |
        relation_types::MOTHER_OF
    )
}

fn is_step_parent_relation(rel_type: &str) -> bool {
    matches!(rel_type,
        relation_types::STEP_PARENT_OF |
        relation_types::STEP_FATHER_OF |
        relation_types::STEP_MOTHER_OF
    )
}

fn is_adoptive_parent_relation(rel_type: &str) -> bool {
    matches!(rel_type,
        relation_types::ADOPTIVE_PARENT_OF |
        relation_types::ADOPTIVE_FATHER_OF |
        relation_types::ADOPTIVE_MOTHER_OF
    )
}

fn is_spouse_relation(rel_type: &str) -> bool {
    matches!(rel_type,
        relation_types::SPOUSE_OF |
        relation_types::HUSBAND_OF |
        relation_types::WIFE_OF |
        relation_types::EX_SPOUSE_OF
    )
}

fn is_sibling_relation(rel_type: &str) -> bool {
    matches!(rel_type,
        relation_types::SIBLING_OF |
        relation_types::BROTHER_OF |
        relation_types::SISTER_OF |
        relation_types::HALF_SIBLING_OF
    )
}

/// Derive Chinese kinship title from relationship path
fn derive_chinese_kinship_title(
    path: &[(&str, PathDirection)],
    _from_gender: Gender,
    to_gender: Gender,
) -> String {
    if path.is_empty() {
        return "自己".to_string();
    }
    
    // Count up/down steps and track intermediate relations
    let mut up_count = 0;
    let mut down_count = 0;
    let mut through_spouse = false;
    let mut through_sibling = false;
    let mut last_parent_gender = Gender::Unknown;
    
    for (rel_type, direction) in path {
        match direction {
            PathDirection::Up => {
                up_count += 1;
                if *rel_type == relation_types::FATHER_OF {
                    last_parent_gender = Gender::Male;
                } else if *rel_type == relation_types::MOTHER_OF {
                    last_parent_gender = Gender::Female;
                }
            }
            PathDirection::Down => down_count += 1,
            PathDirection::Same => {
                if *rel_type == relation_types::SPOUSE_OF 
                    || *rel_type == relation_types::HUSBAND_OF 
                    || *rel_type == relation_types::WIFE_OF {
                    through_spouse = true;
                } else if is_sibling_relation(rel_type) {
                    through_sibling = true;
                }
            }
        }
    }
    
    // Direct relationships
    if !through_spouse && !through_sibling {
        // Direct ancestor
        if down_count == 0 {
            return match up_count {
                1 => match to_gender {
                    Gender::Male => "父亲".to_string(),
                    Gender::Female => "母亲".to_string(),
                    Gender::Unknown => "父母".to_string(),
                },
                2 => match (last_parent_gender, to_gender) {
                    (Gender::Male, Gender::Male) => "爷爷".to_string(),
                    (Gender::Male, Gender::Female) => "奶奶".to_string(),
                    (Gender::Female, Gender::Male) => "外公".to_string(),
                    (Gender::Female, Gender::Female) => "外婆".to_string(),
                    _ => "祖父母".to_string(),
                },
                3 => match to_gender {
                    Gender::Male => "曾祖父".to_string(),
                    Gender::Female => "曾祖母".to_string(),
                    Gender::Unknown => "曾祖父母".to_string(),
                },
                _ => format!("{}世祖", up_count),
            };
        }
        
        // Direct descendant
        if up_count == 0 {
            return match down_count {
                1 => match to_gender {
                    Gender::Male => "儿子".to_string(),
                    Gender::Female => "女儿".to_string(),
                    Gender::Unknown => "子女".to_string(),
                },
                2 => match to_gender {
                    Gender::Male => "孙子".to_string(),
                    Gender::Female => "孙女".to_string(),
                    Gender::Unknown => "孙辈".to_string(),
                },
                3 => match to_gender {
                    Gender::Male => "曾孙".to_string(),
                    Gender::Female => "曾孙女".to_string(),
                    Gender::Unknown => "曾孙辈".to_string(),
                },
                _ => format!("{}世孙", down_count),
            };
        }
    }
    
    // Spouse
    if through_spouse && up_count == 0 && down_count == 0 {
        return match to_gender {
            Gender::Male => "丈夫".to_string(),
            Gender::Female => "妻子".to_string(),
            Gender::Unknown => "配偶".to_string(),
        };
    }
    
    // Sibling
    if through_sibling && up_count == 0 && down_count == 0 {
        return match to_gender {
            Gender::Male => "兄弟".to_string(),
            Gender::Female => "姐妹".to_string(),
            Gender::Unknown => "兄弟姐妹".to_string(),
        };
    }
    
    // Uncle/Aunt (up 1, sibling, then optionally spouse)
    if up_count == 1 && through_sibling && down_count == 0 {
        return match (last_parent_gender, to_gender) {
            (Gender::Male, Gender::Male) => "叔伯".to_string(),
            (Gender::Male, Gender::Female) => "姑姑".to_string(),
            (Gender::Female, Gender::Male) => "舅舅".to_string(),
            (Gender::Female, Gender::Female) => "姨妈".to_string(),
            _ => "叔伯姑姨".to_string(),
        };
    }
    
    // Nephew/Niece (sibling then down 1)
    if through_sibling && down_count == 1 && up_count == 0 {
        return match to_gender {
            Gender::Male => "侄子/外甥".to_string(),
            Gender::Female => "侄女/外甥女".to_string(),
            Gender::Unknown => "侄辈".to_string(),
        };
    }
    
    // Cousin (up 1, sibling, down 1)
    if up_count == 1 && through_sibling && down_count == 1 {
        return match (last_parent_gender, to_gender) {
            (Gender::Male, Gender::Male) => "堂兄弟".to_string(),
            (Gender::Male, Gender::Female) => "堂姐妹".to_string(),
            (Gender::Female, Gender::Male) => "表兄弟".to_string(),
            (Gender::Female, Gender::Female) => "表姐妹".to_string(),
            _ => "堂/表兄弟姐妹".to_string(),
        };
    }
    
    // In-laws through spouse
    if through_spouse {
        if up_count == 1 && down_count == 0 {
            return match to_gender {
                Gender::Male => "公公/岳父".to_string(),
                Gender::Female => "婆婆/岳母".to_string(),
                Gender::Unknown => "公婆/岳父母".to_string(),
            };
        }
        if down_count == 1 && up_count == 0 {
            return match to_gender {
                Gender::Male => "女婿".to_string(),
                Gender::Female => "儿媳".to_string(),
                Gender::Unknown => "儿媳/女婿".to_string(),
            };
        }
    }
    
    // Generic fallback
    let gen_diff = up_count as i32 - down_count as i32;
    if gen_diff > 0 {
        format!("{}辈长辈", gen_diff)
    } else if gen_diff < 0 {
        format!("{}辈晚辈", -gen_diff)
    } else {
        "平辈亲属".to_string()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::social::store_v2::SocialStoreV2Config;
    use crate::social::types::PersonInput;
    use tempfile::tempdir;
    
    fn create_test_store() -> SocialStoreV2 {
        let dir = tempdir().unwrap();
        let config = SocialStoreV2Config::new(dir.path())
            .with_shard_count(4)
            .with_wal(false);
        SocialStoreV2::new(config)
    }
    
    fn add_person_with_gender(store: &SocialStoreV2, name: &str, gender: Gender) -> Entity {
        let mut props = BTreeMap::new();
        props.insert("gender".to_string(), serde_json::json!(gender.as_str()));
        
        store.add_person(PersonInput {
            id: None,
            name: name.to_string(),
            avatar: None,
            description: None,
            phone: None,
            email: None,
            wechat: None,
            properties: props,
        })
    }
    
    #[test]
    fn test_parent_child_relationship() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let father = add_person_with_gender(&store, "张明", Gender::Male);
        let mother = add_person_with_gender(&store, "李芳", Gender::Female);
        let child = add_person_with_gender(&store, "张小明", Gender::Male);
        
        family.add_parent_child(&father.id, &child.id);
        family.add_parent_child(&mother.id, &child.id);
        
        // Test get_parents
        let parents = family.get_parents(&child.id);
        assert_eq!(parents.len(), 2);
        
        // Test get_father/get_mother
        let f = family.get_father(&child.id).unwrap();
        assert_eq!(f.name, "张明");
        
        let m = family.get_mother(&child.id).unwrap();
        assert_eq!(m.name, "李芳");
        
        // Test get_children
        let children = family.get_children(&father.id);
        assert_eq!(children.len(), 1);
        assert_eq!(children[0].name, "张小明");
    }
    
    #[test]
    fn test_spouse_relationship() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let husband = add_person_with_gender(&store, "张明", Gender::Male);
        let wife = add_person_with_gender(&store, "李芳", Gender::Female);
        
        family.add_spouse(&husband.id, &wife.id);
        
        // Test get_spouse from both directions
        let spouse1 = family.get_spouse(&husband.id).unwrap();
        assert_eq!(spouse1.name, "李芳");
        
        let spouse2 = family.get_spouse(&wife.id).unwrap();
        assert_eq!(spouse2.name, "张明");
    }
    
    #[test]
    fn test_sibling_relationship() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let father = add_person_with_gender(&store, "张大山", Gender::Male);
        let child1 = add_person_with_gender(&store, "张明", Gender::Male);
        let child2 = add_person_with_gender(&store, "张红", Gender::Female);
        
        family.add_parent_child(&father.id, &child1.id);
        family.add_parent_child(&father.id, &child2.id);
        
        // Siblings should be inferred from shared parent
        let siblings = family.get_siblings(&child1.id);
        assert_eq!(siblings.len(), 1);
        assert_eq!(siblings[0].name, "张红");
    }
    
    #[test]
    fn test_grandparents() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let grandpa = add_person_with_gender(&store, "张大山", Gender::Male);
        let grandma = add_person_with_gender(&store, "李秀英", Gender::Female);
        let father = add_person_with_gender(&store, "张明", Gender::Male);
        let child = add_person_with_gender(&store, "张小明", Gender::Male);
        
        family.add_parent_child(&grandpa.id, &father.id);
        family.add_parent_child(&grandma.id, &father.id);
        family.add_parent_child(&father.id, &child.id);
        
        let grandparents = family.get_grandparents(&child.id);
        assert_eq!(grandparents.len(), 2);
        
        let paternal_gf = family.get_paternal_grandfather(&child.id).unwrap();
        assert_eq!(paternal_gf.name, "张大山");
        
        let paternal_gm = family.get_paternal_grandmother(&child.id).unwrap();
        assert_eq!(paternal_gm.name, "李秀英");
    }
    
    #[test]
    fn test_calculate_relationship() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let father = add_person_with_gender(&store, "张明", Gender::Male);
        let child = add_person_with_gender(&store, "张小明", Gender::Male);
        
        family.add_parent_child(&father.id, &child.id);
        
        // Child to father
        let path = family.calculate_relationship(&child.id, &father.id).unwrap();
        assert_eq!(path.generation_diff, 1);
        assert_eq!(path.relationship, "父亲");
        
        // Father to child
        let path2 = family.calculate_relationship(&father.id, &child.id).unwrap();
        assert_eq!(path2.generation_diff, -1);
        assert_eq!(path2.relationship, "儿子");
    }
    
    #[test]
    fn test_family_tree_building() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        let grandpa = add_person_with_gender(&store, "张大山", Gender::Male);
        let father = add_person_with_gender(&store, "张明", Gender::Male);
        let child = add_person_with_gender(&store, "张小明", Gender::Male);
        
        family.add_parent_child(&grandpa.id, &father.id);
        family.add_parent_child(&father.id, &child.id);
        
        let tree = family.build_family_tree(&father.id, 2, 2).unwrap();
        assert_eq!(tree.members.len(), 3);
        assert_eq!(tree.total_generations, 3);
    }
    
    #[test]
    fn test_cousins() {
        let store = create_test_store();
        let family = FamilyTreeMatcher::new(&store);
        
        // Grandparent
        let grandpa = add_person_with_gender(&store, "张大山", Gender::Male);
        
        // Two children (siblings)
        let father = add_person_with_gender(&store, "张明", Gender::Male);
        let uncle = add_person_with_gender(&store, "张强", Gender::Male);
        
        // Their children (cousins)
        let me = add_person_with_gender(&store, "张小明", Gender::Male);
        let cousin = add_person_with_gender(&store, "张小强", Gender::Male);
        
        family.add_parent_child(&grandpa.id, &father.id);
        family.add_parent_child(&grandpa.id, &uncle.id);
        family.add_parent_child(&father.id, &me.id);
        family.add_parent_child(&uncle.id, &cousin.id);
        
        let cousins = family.get_cousins(&me.id);
        assert_eq!(cousins.len(), 1);
        assert_eq!(cousins[0].name, "张小强");
    }
}
