"""Excel employee import: validated upsert, SSO default, hierarchy in second pass."""
from collections import Counter
from io import BytesIO, StringIO
import csv
import re
import openpyxl
from sqlalchemy import func
from app.extensions import db
from app.models import Employee, User, Role, Department, BusinessUnit, Designation, Band, City, Location

HEADERS = ["Employee ID", "Full Name", "Official EMail ID", "Current Designation", "Band", "Current Office Area", "Office Location Code", "Direct Manager Name", "Direct Manager Employee ID", "Direct Manager Email ID", "HOD Employee Name", "HOD Employee ID", "Assigned Weekly Off", "Personal Mobile Number", "Departments Hierarchy_1_Name", "Departments Hierarchy_2_Name", "Departments Hierarchy_3_Name", "Office State", "Address"]

def clean(value):
    if value is None: return ""
    return str(value).strip()

def master(model, name, cache):
    name = clean(name)
    if not name: return None
    key = (model.__name__, name.casefold())
    if key not in cache:
        item = model.query.filter(func.lower(model.name) == name.lower()).first()
        if not item:
            if model in (Department, BusinessUnit):
                prefix = "DEP" if model is Department else "BU"
                import hashlib
                code = prefix + hashlib.sha1(name.casefold().encode()).hexdigest()[:16].upper()
                item = model(code=code, name=name)
            else: item = model(name=name)
            db.session.add(item)
            db.session.flush()
        cache[key] = item.id
    return cache[key]

def import_employee_workbook(stream, dry_run=True):
    try: book = openpyxl.load_workbook(BytesIO(stream.read()), read_only=True, data_only=True)
    except Exception as exc: raise ValueError("Invalid Excel workbook: " + str(exc))
    sheet = book.active
    it = sheet.iter_rows(values_only=True)
    headers = [clean(x) for x in next(it, [])]
    if headers != HEADERS: raise ValueError("Column headers do not match the supplied Final Employee List template.")
    rows = []
    errors = []
    for line, cells in enumerate(it, 2):
        if not any(x is not None and clean(x) for x in cells): continue
        r = dict(zip(HEADERS, (clean(x) for x in cells)))
        code, email, name = r["Employee ID"], r["Official EMail ID"].lower(), r["Full Name"]
        if not code or not name or not re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", email): errors.append("Row %s: missing/invalid ID, name or email" % line)
        r["Official EMail ID"] = email
        rows.append(r)
    for field in ("Employee ID", "Official EMail ID"):
        counts = Counter(r[field].lower() for r in rows)
        duplicates = [v for v,c in counts.items() if c > 1]
        if duplicates: errors.append("Duplicate %s: %s" % (field, ", ".join(duplicates[:8])))
    if errors: raise ValueError("Import blocked: " + "; ".join(errors[:20]))
    codes = [r["Employee ID"] for r in rows]
    emails = [r["Official EMail ID"] for r in rows]
    employees = {e.employee_code:e for e in Employee.query.filter(Employee.employee_code.in_(codes)).all()}
    users = {u.official_email.lower():u for u in User.query.filter(func.lower(User.official_email).in_(emails)).all()}
    conflicts=[]
    for r in rows:
        emp=employees.get(r["Employee ID"]); user=users.get(r["Official EMail ID"])
        if emp and user and emp.user_id != user.id: conflicts.append(r["Employee ID"] + ": email belongs to another user")
        if emp and emp.official_email.lower() != r["Official EMail ID"] and user: conflicts.append(r["Employee ID"] + ": email collision")
        if not emp and user and user.employee: conflicts.append(r["Employee ID"] + ": email belongs to another employee")
    if conflicts: raise ValueError("Import blocked: " + "; ".join(conflicts[:20]))
    result={"total":len(rows), "create":sum(r["Employee ID"] not in employees for r in rows), "update":sum(r["Employee ID"] in employees for r in rows), "missing_managers":[], "dry_run":dry_run}
    known=set(employees) | set(codes)
    email_to_code = {r["Official EMail ID"]: r["Employee ID"] for r in rows}
    existing_manager_emails = {e.official_email.lower(): e.employee_code for e in Employee.query.filter(func.lower(Employee.official_email).in_([r["Direct Manager Email ID"].lower() for r in rows if r["Direct Manager Email ID"]])).all() if e.official_email}
    email_to_code.update(existing_manager_emails)
    missing_rows = []
    for r in rows:
        mid=r["Direct Manager Employee ID"]
        mail=r["Direct Manager Email ID"].lower()
        resolved = (mid and mid in known) or (mail and mail in email_to_code)
        if (mid or mail) and not resolved:
            result["missing_managers"].append(r["Employee ID"]+" -> "+(mid or mail))
            missing_rows.append({"employee_id":r["Employee ID"], "employee_name":r["Full Name"], "employee_email":r["Official EMail ID"], "manager_id":mid, "manager_email":mail})
    result["missing_manager_rows"] = missing_rows
    if dry_run: return result
    cache={}
    employee_role=Role.query.filter_by(code="EMPLOYEE").first()
    try:
        for r in rows:
            code=r["Employee ID"];email=r["Official EMail ID"];emp=employees.get(code)
            if emp:
                user=emp.user
                # Preserve existing explicit LOCAL credentials and elevated role assignments.
            else:
                user=users.get(email)
                if not user:
                    user=User(official_email=email, auth_method="SSO", is_active=True)
                    if employee_role: user.roles=[employee_role]
                    db.session.add(user);db.session.flush()
                emp=Employee(user_id=user.id, employee_code=code, full_name=r["Full Name"], official_email=email, is_active=True, eligible_for_portal=True)
                db.session.add(emp);db.session.flush();employees[code]=emp
            if user.official_email.lower()!=email and email in users: raise ValueError("Email collision: "+email)
            user.official_email=email;emp.official_email=email;emp.full_name=r["Full Name"]
            emp.mobile=r["Personal Mobile Number"] or None
            emp.designation_id=master(Designation,r["Current Designation"],cache)
            emp.band_id=master(Band,r["Band"],cache)
            emp.department_id=master(Department,r["Departments Hierarchy_3_Name"] or r["Departments Hierarchy_2_Name"] or r["Departments Hierarchy_1_Name"],cache)
            emp.business_unit_id=master(BusinessUnit,r["Departments Hierarchy_1_Name"],cache)
            emp.department_hierarchy_1=r["Departments Hierarchy_1_Name"] or None
            emp.department_hierarchy_2=r["Departments Hierarchy_2_Name"] or None
            emp.department_hierarchy_3=r["Departments Hierarchy_3_Name"] or None
            emp.office_area=r["Current Office Area"] or None
            emp.office_location_code=r["Office Location Code"] or None
            emp.office_state=r["Office State"] or None
            emp.office_address=r["Address"] or None
            emp.weekly_off=r["Assigned Weekly Off"] or None
            emp.manager_source_code=r["Direct Manager Employee ID"] or None
            emp.manager_source_email=r["Direct Manager Email ID"] or None
            emp.hod_source_code=r["HOD Employee ID"] or None
            emp.hod_name=r["HOD Employee Name"] or None
        db.session.flush()
        for r in rows:
            emp=employees[r["Employee ID"]]
            manager=employees.get(r["Direct Manager Employee ID"])
            if not manager and r["Direct Manager Email ID"]:
                fallback_code = email_to_code.get(r["Direct Manager Email ID"].lower())
                if fallback_code:
                    manager=employees.get(fallback_code) or Employee.query.filter_by(employee_code=fallback_code).first()
            if not manager and r["Direct Manager Employee ID"]:
                manager=Employee.query.filter_by(employee_code=r["Direct Manager Employee ID"]).first()
            if manager and manager.id != emp.id: emp.manager_id=manager.id
            elif r["Direct Manager Employee ID"] or r["Direct Manager Email ID"]:
                emp.manager_id = None
        db.session.commit()
    except Exception:
        db.session.rollback();raise
    return result
