import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
import os
import re
from datetime import datetime

class KTGioiCleaner:
    def __init__(self):
        # Base technician mapping for normalization
        self.kythuat_map = {
            'đỗ quang thủy': 'Đỗ Quang Thủy',
            'đỗ quang thuỷ': 'Đỗ Quang Thủy',
            'đõ quang thuỷ': 'Đỗ Quang Thủy',
            'trần dũng': 'Trần Dũng',
            'trần dung': 'Trần Dũng',
            'trần văn thưởng': 'Trần Văn Thưởng',
            'nguyễn phú vĩnh': 'Nguyễn Phú Vĩnh',
            'phú vĩnh': 'Nguyễn Phú Vĩnh',
            'võ quốc khởi': 'Võ Quốc Khởi',
            'lê xuân tương': 'Lê Xuân Tương',
            'trương văn trường': 'Trương Văn Trường',
            'nguyễn văn hoan': 'Nguyễn Văn Hoan',
            'nguyễn hữu lợi': 'Nguyễn Hữu Lợi',
            'nông đức trường': 'Nông Đức Trường',
            'trần văn tùng': 'Trần Văn Tùng',
            'phạm văn linh': 'Phạm Văn Linh',
            'lê văn hòa': 'Lê Văn Hòa',
            'nguyễn trọng phong': 'Nguyễn Trọng Phong',
            'hồ tiến sỹ': 'Hồ Tiến Sĩ',
            'nguyễn duy tài': 'Nguyễn Duy Tài',
            'lê văn thành': 'Lê Văn Thành',
            'tiến thành sơn': 'Tiến Thành Sơn',
            'phan văn việt': 'Phan Văn Việt',
            'phạm văn thiêm': 'Phạm Văn Thiêm',
            'hồ duy khánh': 'Hồ Duy Khánh',
            'triệu văn đông': 'Triệu Văn Đông',
            'cao ngọc dương': 'Cao Ngọc Dương',
            'hoàng văn sang': 'Hoàng Văn Sang'
        }

    def normalize_kythuat(self, name):
        if name is None:
            return None
        s = str(name).strip()
        if not s:
            return None
        s_lower = s.lower()
        if s_lower in self.kythuat_map:
            return self.kythuat_map[s_lower]
        return s

    def clean_tuan30_sheet(self, input_path):
        wb = openpyxl.load_workbook(input_path, data_only=True)
        ws = wb["TUAN 30"]
        
        cleaned_rows = []
        
        current_stt = None
        current_nha_may = None
        current_ky_thuat = None
        
        for r in range(5, ws.max_row + 1):
            row_vals = [ws.cell(r, col).value for col in range(1, 14)]
            # Skip completely empty rows
            if all(x is None or str(x).strip() == "" for x in row_vals):
                continue
                
            stt = row_vals[0]
            nha_may = row_vals[1]
            ky_thuat = row_vals[2]
            ma_so_mau = row_vals[3]
            khach_hang = row_vals[4]
            
            loai_moi = row_vals[5]
            loai_nhan = row_vals[6]
            loai_ct = row_vals[7]
            loai_bo_val = row_vals[8]
            
            status_ky = row_vals[9]
            dh_val = row_vals[10]
            status_kd = row_vals[11]
            ghi_chu = row_vals[12]
            
            # Propagation
            if stt is not None:
                current_stt = int(float(str(stt)))
            if nha_may is not None and str(nha_may).strip():
                current_nha_may = str(nha_may).strip()
            if ky_thuat is not None and str(ky_thuat).strip():
                current_ky_thuat = str(ky_thuat).strip()
                
            # If the row is just a note about supporting/not making samples (e.g. Lê Văn Hòa, Nguyễn Duy Tài, Hoàng Văn Sang)
            is_support_only = False
            if ma_so_mau is None and khach_hang is None and loai_moi is None and loai_nhan is None and loai_ct is None and loai_bo_val is None:
                is_support_only = True
                
            loai_mau = None
            sp = None
            so_luong = None
            
            if not is_support_only:
                # Determine type
                if loai_moi is not None and str(loai_moi).strip().upper() == 'X':
                    loai_mau = 'Mới'
                    so_luong = 1
                elif loai_nhan is not None and str(loai_nhan).strip().upper() == 'X':
                    loai_mau = 'Nhân'
                    so_luong = 1
                elif loai_ct is not None and str(loai_ct).strip().upper() == 'X':
                    loai_mau = 'Cạnh tranh'
                    so_luong = 1
                elif loai_bo_val is not None:
                    loai_mau = 'Bộ'
                    # Parse loai_bo_val
                    val_str = str(loai_bo_val).strip()
                    # Try to match patterns like "6", "1 TỦ", "8 GHẾ"
                    m = re.match(r'^(\d+)\s*(.*)$', val_str)
                    if m:
                        so_luong = int(m.group(1))
                        sp_name = m.group(2).strip().upper()
                        if sp_name:
                            sp = sp_name
                    else:
                        sp = val_str
                        so_luong = 1
                        
            # Determine status
            trang_thai = None
            if not is_support_only:
                if status_ky is not None and str(status_ky).strip().upper() == 'X':
                    trang_thai = 'DK'
                elif status_kd is not None and str(status_kd).strip().upper() == 'X':
                    trang_thai = 'KĐ' # Không đạt
                else:
                    trang_thai = 'HT' # Default completed
                    
            co_dh_final = 'X' if dh_val is not None and str(dh_val).strip().upper() == 'X' else None
            
            # Normalize technician
            tech_normalized = self.normalize_kythuat(current_ky_thuat)
            
            cleaned_rows.append({
                'stt': current_stt,
                'nha_may': current_nha_may,
                'ma_pt': None,
                'ma_nm': str(ma_so_mau).strip() if ma_so_mau is not None else None,
                'khach_hang': str(khach_hang).strip() if khach_hang is not None else None,
                'ngay_nhan': None,
                'ngay_ht': None,
                'loai_mau': loai_mau,
                'sp': sp,
                'so_luong': so_luong,
                'ky_thuat': tech_normalized,
                'trang_thai': trang_thai,
                'co_dh': co_dh_final,
                'ghi_chu': str(ghi_chu).strip() if ghi_chu is not None else None
            })
            
        return cleaned_rows

    def run(self):
        input_file = "TONG HOP MAU KY THUAT CHUYEN LÀM MAU-t30.xlsx"
        # Handle typo in filename if needed
        if not os.path.exists(input_file):
            input_file = "TONG HOP MAU KY THUAT CHUYEN LAM MAU-t30.xlsx"
            
        print("Cleaning specializing technician sheet from:", input_file)
        cleaned_data = self.clean_tuan30_sheet(input_file)
        
        # Save to output excel
        output_dir = "da lam sach"
        os.makedirs(output_dir, exist_ok=True)
        output_path = os.path.join(output_dir, "Tuan_30_KT-GIOI_DA-LAM-SACH.xlsx")
        
        wb_out = openpyxl.Workbook()
        ws_out = wb_out.active
        ws_out.title = "Làm sạch"
        
        headers = ["Stt", "Nhà máy", "Mã PT/KH", "Mã NM", "Khách hàng", "Ngày nhận", "Ngày HT", "Loại mẫu", "SP", "Số lượng", "Kỹ thuật", "Trạng thái", "Có ĐH", "Ghi chú"]
        header_font = Font(bold=True, size=11)
        header_fill = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")
        header_alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        thin_border = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )
        
        for col_idx, h in enumerate(headers, 1):
            cell = ws_out.cell(1, col_idx, h)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = header_alignment
            cell.border = thin_border
            
        for row_idx, r in enumerate(cleaned_data, 2):
            row_data = [
                r['stt'],
                r['nha_may'],
                r['ma_pt'],
                r['ma_nm'],
                r['khach_hang'],
                r['ngay_nhan'],
                r['ngay_ht'],
                r['loai_mau'],
                r['sp'],
                r['so_luong'],
                r['ky_thuat'],
                r['trang_thai'],
                r['co_dh'],
                r['ghi_chu']
            ]
            for col_idx, val in enumerate(row_data, 1):
                cell = ws_out.cell(row_idx, col_idx, val)
                cell.border = thin_border
                if col_idx == 1:
                    cell.alignment = Alignment(horizontal='center')
                elif col_idx == 10:
                    cell.alignment = Alignment(horizontal='center')
                    
        col_widths = [5, 18, 18, 20, 18, 14, 14, 10, 25, 8, 30, 10, 8, 40]
        for i, w in enumerate(col_widths, 1):
            ws_out.column_dimensions[get_column_letter(i)].width = w
            
        wb_out.save(output_path)
        print("Cleaned file saved successfully to:", output_path)
        
        # Write Markdown Report
        report_path = os.path.join(output_dir, "Bao_cao_lam_sach_Tuan30_KT-GIOI.md")
        
        # Calculate stats
        types_count = {'Mới': 0, 'Nhân': 0, 'Bộ': 0, 'Cạnh tranh': 0, None: 0}
        status_count = {'DK': 0, 'HT': 0, 'KĐ': 0, None: 0}
        total_qty = 0
        
        for r in cleaned_data:
            lm = r['loai_mau']
            tt = r['trang_thai']
            qty = r['so_luong']
            if lm in types_count:
                types_count[lm] += 1
            else:
                types_count[lm] = types_count.get(lm, 0) + 1
            if tt in status_count:
                status_count[tt] += 1
            else:
                status_count[tt] = status_count.get(tt, 0) + 1
            if qty:
                total_qty += qty
                
        report_content = f"""# BÁO CÁO LÀM SẠCH DỮ LIỆU - TUẦN 30 (KỸ THUẬT CHUYÊN LÀM MẪU)

## Thông tin chung
- **File gốc**: TONG HOP MAU KY THUAT CHUYEN LAM MAU-t30.xlsx (Sheet: TUAN 30)
- **File sạch đầu ra**: Tuan_30_KT-GIOI_DA-LAM-SACH.xlsx
- **Ngày xử lý**: {datetime.now().strftime('%d/%m/%Y')}

## Thống kê dữ liệu làm mẫu
- **Tổng số dòng dữ liệu**: {len(cleaned_data)}
- **Tổng sản lượng sản phẩm làm mẫu**: {total_qty} cái

| Loại mẫu | Số lượng (dòng) | Trạng thái | Số lượng (dòng) |
|----------|----------|------------|----------|
| Mẫu Mới | {types_count['Mới']} | Đã Ký (DK) | {status_count['DK']} |
| Mẫu Nhân | {types_count['Nhân']} | Hoàn Thành (HT) | {status_count['HT']} |
| Mẫu Bộ | {types_count['Bộ']} | Không Đạt (KĐ) | {status_count['KĐ']} |
| Mẫu Cạnh tranh | {types_count['Cạnh tranh']} | Chưa rõ | {status_count[None]} |
| Hỗ trợ chuyền/Không làm mẫu | {types_count[None]} | | |
"""
        with open(report_path, "w", encoding="utf-8") as f:
            f.write(report_content)
        print("Markdown report saved successfully to:", report_path)

if __name__ == "__main__":
    cleaner = KTGioiCleaner()
    cleaner.run()
