#!/usr/bin/env python3
"""
Advanced Directory Structure Excel Generator
With tree visualization and detailed statistics
"""

import os
import sys
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from collections import defaultdict
from datetime import datetime


class AdvancedDirectoryExcel:
    """Advanced Excel generator with tree view and statistics"""
    
    # Extended color palette
    COLORS = {
        'primary': '2E86AB',
        'secondary': 'A23B72',
        'success': '28A745',
        'warning': 'FFC107',
        'danger': 'DC3545',
        'info': '17A2B8',
        
        # File type colors
        'php': 'F8D7DA',
        'javascript': 'FFF3CD',
        'css': 'D1ECF1',
        'typescript': 'E2E3E5',
        'json': 'F3E5AB',
        'html': 'FFE4C4',
        'python': '98FB98',
        'sql': 'DDA0DD',
        'markdown': 'E8F4FD',
        'config': 'F0E68C',
        'image': 'FFB6C1',
        'archive': 'FFD700',
        'default': 'FFFFFF',
        
        # Folder colors by depth
        'folder_depth_0': 'C8E6C9',  # Root folders - green
        'folder_depth_1': 'FFF9C4',  # Level 1 - yellow
        'folder_depth_2': 'BBDEFB',  # Level 2 - blue
        'folder_depth_3': 'E1BEE7',  # Level 3 - purple
    }
    
    def __init__(self, root_path):
        self.root_path = Path(root_path)
        self.workbook = Workbook()
        self.workbook.remove(self.workbook.active)
        self.stats = defaultdict(int)
        
    def get_file_color(self, file_path):
        """Get color based on file extension"""
        ext = Path(file_path).suffix.lower()
        
        color_map = {
            '.php': self.COLORS['php'],
            '.js': self.COLORS['javascript'],
            '.jsx': self.COLORS['javascript'],
            '.ts': self.COLORS['typescript'],
            '.tsx': self.COLORS['typescript'],
            '.css': self.COLORS['css'],
            '.scss': self.COLORS['css'],
            '.json': self.COLORS['json'],
            '.html': self.COLORS['html'],
            '.htm': self.COLORS['html'],
            '.py': self.COLORS['python'],
            '.sql': self.COLORS['sql'],
            '.md': self.COLORS['markdown'],
            '.xml': self.COLORS['config'],
            '.yml': self.COLORS['config'],
            '.yaml': self.COLORS['config'],
            '.jpg': self.COLORS['image'],
            '.jpeg': self.COLORS['image'],
            '.png': self.COLORS['image'],
            '.gif': self.COLORS['image'],
            '.svg': self.COLORS['image'],
            '.rar': self.COLORS['archive'],
            '.zip': self.COLORS['archive'],
            '.tar': self.COLORS['archive'],
            '.gz': self.COLORS['archive'],
        }
        
        return color_map.get(ext, self.COLORS['default'])
    
    def get_folder_color(self, depth):
        """Get color based on folder depth"""
        depth_colors = [
            self.COLORS['folder_depth_0'],
            self.COLORS['folder_depth_1'],
            self.COLORS['folder_depth_2'],
            self.COLORS['folder_depth_3'],
        ]
        return depth_colors[min(depth, len(depth_colors) - 1)]
    
    def scan_directory_tree(self, path, max_depth=None, current_depth=0, parent_prefix='', is_last=True):
        """Generate tree structure with proper formatting"""
        lines = []
        
        if max_depth is not None and current_depth > max_depth:
            return lines
        
        try:
            items = sorted(path.iterdir(), key=lambda x: (not x.is_dir(), x.name))
            
            for i, item in enumerate(items):
                is_item_last = (i == len(items) - 1)
                
                # Build tree prefix
                if current_depth == 0:
                    tree_prefix = '📦 '
                else:
                    connector = '└── ' if is_item_last else '├── '
                    tree_prefix = parent_prefix + connector
                
                item_info = {
                    'name': item.name,
                    'type': 'folder' if item.is_dir() else 'file',
                    'path': str(item),
                    'depth': current_depth,
                    'tree_line': tree_prefix + ('📁 ' if item.is_dir() else '📄 ') + item.name,
                    'extension': item.suffix if item.is_file() else None,
                    'is_last': is_item_last
                }
                
                lines.append(item_info)
                self.stats[item.type] += 1
                
                if item.is_dir():
                    # Build extension prefix for children
                    if current_depth == 0:
                        extension = ''
                    elif is_item_last:
                        extension = parent_prefix + '    '
                    else:
                        extension = parent_prefix + '│   '
                    
                    lines.extend(self.scan_directory_tree(
                        item, max_depth, current_depth + 1, extension, is_item_last
                    ))
                    
        except PermissionError:
            pass
        except Exception as e:
            print(f"Error scanning {path}: {e}")
            
        return lines
    
    def create_styled_sheet(self, sheet_name, items, branch_path):
        """Create a styled sheet with tree view"""
        ws = self.workbook.create_sheet(title=sheet_name[:31])
        
        # Styles
        header_fill = PatternFill(start_color=self.COLORS['primary'], 
                                   end_color=self.COLORS['primary'], 
                                   fill_type='solid')
        header_font = Font(bold=True, color='FFFFFF', size=11)
        thin_border = Border(
            left=Side(style='thin', color='CCCCCC'),
            right=Side(style='thin', color='CCCCCC'),
            top=Side(style='thin', color='CCCCCC'),
            bottom=Side(style='thin', color='CCCCCC')
        )
        
        # Title row
        ws.merge_cells('A1:E1')
        title = ws['A1']
        title.value = f"📂 {sheet_name}"
        title.font = Font(bold=True, size=14, color=self.COLORS['primary'])
        title.alignment = Alignment(horizontal='left', vertical='center')
        ws.row_dimensions[1].height = 25
        
        # Stats row
        folders = sum(1 for i in items if i['type'] == 'folder')
        files = sum(1 for i in items if i['type'] == 'file')
        
        ws.merge_cells('A2:E2')
        stats_cell = ws['A2']
        stats_cell.value = f"📊 Total: {len(items)} items | 📁 {folders} folders | 📄 {files} files"
        stats_cell.font = Font(size=10, italic=True, color='666666')
        stats_cell.alignment = Alignment(horizontal='left')
        ws.row_dimensions[2].height = 20
        
        # Headers (بدون Path)
        headers = ['#', 'Tree View', 'Type', 'Name', 'Extension']
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=4, column=col, value=header)
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = Alignment(horizontal='center', vertical='center')
            cell.border = thin_border
        ws.row_dimensions[4].height = 22
        
        # Column widths (بدون ستون Path)
        ws.column_dimensions['A'].width = 5
        ws.column_dimensions['B'].width = 55
        ws.column_dimensions['C'].width = 8
        ws.column_dimensions['D'].width = 40
        ws.column_dimensions['E'].width = 15
        
        # Add items
        for idx, item in enumerate(items, 1):
            row = idx + 4
            
            # Determine fill color
            if item['type'] == 'folder':
                fill_color = self.get_folder_color(item['depth'])
            else:
                fill_color = self.get_file_color(item['path'])
            
            item_fill = PatternFill(start_color=fill_color,
                                     end_color=fill_color,
                                     fill_type='solid')
            
            # Type icon
            type_icon = '📁' if item['type'] == 'folder' else '📄'
            
            # Row data (بدون Path)
            row_data = [
                idx,
                item['tree_line'],
                type_icon,
                item['name'],
                item['extension'] or ''
            ]
            
            for col, value in enumerate(row_data, 1):
                cell = ws.cell(row=row, column=col, value=value)
                cell.fill = item_fill
                cell.border = thin_border
                cell.alignment = Alignment(vertical='center')
                
                if col == 2:  
                    cell.font = Font(
                        family='Consolas',
                        size=10,
                        bold=item['type'] == 'folder',
                        color='000080' if item['type'] == 'folder' else '333333'
                    )
                elif col == 4:  
                    cell.font = Font(
                        bold=item['type'] == 'folder',
                        color='000080' if item['type'] == 'folder' else '333333'
                    )
        
        # Freeze header
        ws.freeze_panes = 'A5'
        
        return ws
    
    def create_summary_sheet(self, branches):
        """Create comprehensive summary sheet"""
        ws = self.workbook.create_sheet(title='📋 Summary', index=0)
        
        # Title
        ws.merge_cells('A1:F1')
        title = ws['A1']
        title.value = f"📊 Directory Structure Report - {self.root_path.name}"
        title.font = Font(bold=True, size=16, color=self.COLORS['primary'])
        title.alignment = Alignment(horizontal='center', vertical='center')
        ws.row_dimensions[1].height = 35
        
        # Generated date
        ws.merge_cells('A2:F2')
        date_cell = ws['A2']
        date_cell.value = f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        date_cell.font = Font(size=10, italic=True, color='888888')
        date_cell.alignment = Alignment(horizontal='right')
        
        # Overall statistics
        ws.merge_cells('A4:F4')
        stats_title = ws['A4']
        stats_title.value = "📈 Overall Statistics"
        stats_title.font = Font(bold=True, size=12, color=self.COLORS['primary'])
        
        # Stats headers
        stats_headers = ['Branch', 'Total Items', 'Folders', 'Files', 'Max Depth', 'Status']
        for col, header in enumerate(stats_headers, 1):
            cell = ws.cell(row=5, column=col, value=header)
            cell.fill = PatternFill(start_color=self.COLORS['primary'], 
                                    end_color=self.COLORS['primary'], 
                                    fill_type='solid')
            cell.font = Font(bold=True, color='FFFFFF')
            cell.alignment = Alignment(horizontal='center')
        
        # Branch statistics
        for idx, branch in enumerate(branches, 1):
            items = self.scan_directory_tree(branch)
            folders = sum(1 for i in items if i['type'] == 'folder')
            files = sum(1 for i in items if i['type'] == 'file')
            max_depth = max((i['depth'] for i in items), default=0)
            
            row_data = [
                branch.name,
                len(items),
                folders,
                files,
                max_depth,
                '✅ OK'
            ]
            
            for col, value in enumerate(row_data, 1):
                cell = ws.cell(row=idx + 5, column=col, value=value)
                cell.alignment = Alignment(horizontal='center' if col != 1 else 'left')
                if col == 1:
                    cell.font = Font(bold=True)
        
        # Column widths
        ws.column_dimensions['A'].width = 25
        ws.column_dimensions['B'].width = 12
        ws.column_dimensions['C'].width = 10
        ws.column_dimensions['D'].width = 10
        ws.column_dimensions['E'].width = 12
        ws.column_dimensions['F'].width = 10
        
        # Color legend
        legend_start = len(branches) + 8
        ws.cell(row=legend_start, column=1, value='🎨 Color Legend:').font = Font(bold=True, size=11)
        
        legend_items = [
            ('📁 Folders (Level 0)', self.COLORS['folder_depth_0']),
            ('📁 Folders (Level 1)', self.COLORS['folder_depth_1']),
            ('📁 Folders (Level 2)', self.COLORS['folder_depth_2']),
            ('📁 Folders (Level 3)', self.COLORS['folder_depth_3']),
            ('📄 PHP Files', self.COLORS['php']),
            ('📄 JavaScript Files', self.COLORS['javascript']),
            ('📄 CSS Files', self.COLORS['css']),
            ('📄 TypeScript Files', self.COLORS['typescript']),
            ('📄 Python Files', self.COLORS['python']),
            ('📄 Config Files', self.COLORS['config']),
            ('📄 Other Files', self.COLORS['default']),
        ]
        
        for i, (name, color) in enumerate(legend_items):
            row = legend_start + i + 1
            color_cell = ws.cell(row=row, column=2, value=name)
            color_cell.fill = PatternFill(start_color=color, end_color=color, fill_type='solid')
            color_cell.border = Border(
                left=Side(style='thin'),
                right=Side(style='thin'),
                top=Side(style='thin'),
                bottom=Side(style='thin')
            )
        
        return ws
    
    def generate(self, output_file='directory_structure.xlsx'):
        """Generate the complete Excel file"""
        print(f"🔍 Scanning: {self.root_path}")
        
        # Get branches
        branches = []
        try:
            for item in sorted(self.root_path.iterdir()):
                if item.is_dir():
                    branches.append(item)
        except Exception as e:
            print(f"❌ Error: {e}")
            return False
        
        print(f"📦 Found {len(branches)} branches")
        
        # Create summary sheet
        self.create_summary_sheet(branches)
        
        # Create sheet for each branch
        for branch in branches:
            print(f"  📂 Processing: {branch.name}")
            items = self.scan_directory_tree(branch)
            self.create_styled_sheet(branch.name, items, branch)
        
        # Save
        self.workbook.save(output_file)
        print(f"\n✅ Success! File saved: {output_file}")
        return True


def main():
    """Main entry point"""
    print("=" * 60)
    print("📊 Directory Structure to Excel Generator")
    print("=" * 60)
    
    if len(sys.argv) > 1:
        root_path = sys.argv[1]
    else:
        root_path = os.getcwd()
    
    output_file = 'directory_structure.xlsx'
    if len(sys.argv) > 2:
        output_file = sys.argv[2]
    
    generator = AdvancedDirectoryExcel(root_path)
    generator.generate(output_file)


if __name__ == '__main__':
    main()