import re
from typing import Dict, List

class WorkExperienceExtractor:
    def __init__(self):
        self.exp_keys = [
            'EXPERIENCE', 'WORK EXPERIENCE', 'EMPLOYMENT HISTORY',
            'PROFESSIONAL EXPERIENCE', 'RELEVANT EXPERIENCE',
            'RESEARCH EXPERIENCE', 'CAREER HISTORY', 'WORK HISTORY',
            'INDUSTRY EXPERIENCE', 'FREELANCE EXPERIENCE', 'INTERNSHIP EXPERIENCE'
        ]

    def extract_work_experience(self, resume_dict: Dict[str, str]) -> List[Dict[str, str]]:
        work_experience = []  # Final output list
        if 'sections' in resume_dict:
            sections = resume_dict['sections']
            
            # Step 1: Find the first matching key from exp_keys
            matching_key = next((key for key in self.exp_keys if key in sections), None)
            
            if matching_key and matching_key in sections:
                work_text = sections[matching_key]  # Get the text of the matching section
                if work_text:  # Ensure it's not empty
                    lines = [line.strip() for line in work_text.split('\n') if line.strip()]  # Split into lines and remove empty ones
                    
                    current_job = {}  # Temp dict for the current job
                    responsibilities = []  # List to collect responsibilities
                    
                    for line in lines:
                        # Step 2: Check if this line contains a title and duration (e.g., "Title at Company | Duration")
                        match = re.search(r'^(.+?)\s*[|]\s*(.+)$', line)  # Pattern for "Title | Duration"
                        if match:
                            # If we have a previous job, save it first
                            if current_job and responsibilities:
                                current_job['responsibilities'] = '\n'.join(responsibilities)
                                work_experience.append(current_job)
                            
                            title_part = match.group(1).strip()  # Extract title 
                            duration_part = match.group(2).strip()  # Extract duration (e.g., "May’21-Jun’22")
                            
                            # Set the current job
                            current_job = {
                                'title': title_part,
                                'duration': duration_part,
                            }
                            responsibilities = []  # Reset responsibilities
                        elif self.is_duration(line):  # Check if this line is just a duration (e.g., "Aug 2024 - Present")
                            if not current_job:
                                # If no title yet, assume this line might be a title (rare case), but skip for now
                                continue
                            current_job['duration'] = line  # Set or overwrite duration
                        else:
                            # Treat as responsibility (e.g., bullet points)
                            cleaned_line = re.sub(r'^[\u2022\-●]\s?', '', line).strip()  # Remove bullets like '•', '-', or '●'
                            if cleaned_line:  # Only add non-empty lines
                                responsibilities.append(cleaned_line)
                    
                    # Add the last job if it exists
                    if current_job and responsibilities:
                        current_job['responsibilities'] = '\n'.join(responsibilities)
                        work_experience.append(current_job)
        
        return work_experience

    def is_duration(self, line: str) -> bool:
        # Regex for common date formats: e.g., "Aug 2024 - Present", "May’21-Jun’22", "Dec’17-Jun’21", "2010 - 2015"
        date_patterns = [
            r'^\w+ \d{4} - \w+ \d{4}',  # e.g., "Aug 2024 - May 2025"
            r'^\w+ \d{4} - Present',   # e.g., "Aug 2024 - Present"
            r'^\w+’\d{2}-\w+’\d{2}',   # e.g., "May’21-Jun’22" (curly apostrophe)
            r'^\w+’\d{2}-Present',     # e.g., "May’21-Present"
            r'^\d{4} - \d{4}',         # e.g., "2017 - 2023"
            r'^\d{4} - Present'        # e.g., "2017 - Present"
        ]
        for pattern in date_patterns:
            if re.match(pattern, line, re.IGNORECASE):
                return True
        return False

i only want the duration and responsibilities