"""
Dummy Data Generator Service.

Generates realistic random test data across all modules for pre-staging testing.
Controlled by ALLOW_DUMMY_DATA environment variable.
"""
import logging
import random
import math
import uuid6
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy.exc import IntegrityError
from app.extensions import db
from app.core.models import User, Role, Permission, Status, Category, Contact, Office, Settings
from app.core.models.employee import Employee
from app.core.models.notification import Notification

logger = logging.getLogger(__name__)

# Sentinel UUID for tracking dummy data origin
DUMMY_CREATOR_ID = '00000000-0000-0000-0000-00000000DEAD'

# --- Random Data Pools ---
FIRST_NAMES = [
    'Andi', 'Budi', 'Citra', 'Dewi', 'Eko', 'Fitri', 'Gilang', 'Hana',
    'Irfan', 'Jasmine', 'Kevin', 'Lina', 'Mira', 'Naufal', 'Olivia',
    'Putra', 'Rina', 'Surya', 'Tari', 'Umar', 'Vina', 'Wawan', 'Yani', 'Zaki'
]
LAST_NAMES = [
    'Pratama', 'Sari', 'Wijaya', 'Kusuma', 'Santoso', 'Handoko', 'Putri',
    'Rahman', 'Setiawan', 'Hidayat', 'Nugroho', 'Wibowo', 'Suryadi', 'Hartono'
]
DEPARTMENTS = ['Engineering', 'Marketing', 'Sales', 'Finance', 'Operations', 'HR', 'Support']
POSITIONS = ['Staff', 'Senior Staff', 'Team Lead', 'Specialist', 'Coordinator', 'Analyst']
COMPANY_NAMES = [
    'PT Maju Bersama', 'CV Karya Utama', 'PT Solusi Digital', 'PT Indo Kreatif',
    'CV Mandiri Jaya', 'PT Techno Nusantara', 'PT Mitra Abadi', 'PT Bintang Perkasa',
    'CV Cipta Karya', 'PT Harmoni Global', 'PT Sinar Harapan', 'PT Daya Cipta'
]
LEAD_TITLES = [
    'Website Redesign', 'Mobile App Development', 'ERP Implementation',
    'Cloud Migration', 'Digital Marketing Campaign', 'Cybersecurity Audit',
    'Data Analytics Platform', 'Custom CRM Build', 'E-Commerce Platform',
    'API Integration Service', 'IT Consulting Retainer', 'Staff Augmentation'
]
PROJECT_TITLES = [
    'Project Alpha', 'Project Beta', 'Project Gamma', 'Project Delta',
    'Project Epsilon', 'Revamp Portal', 'Mobile Commerce', 'Analytics Dashboard'
]
TICKET_SUBJECTS = [
    'Login issue', 'Report not loading', 'Invoice mismatch', 'Cannot access module',
    'Feature request: bulk export', 'Slow dashboard load', 'Data import error',
    'Permission denied error', 'Email notification not received', 'UI display bug'
]
BANKS = ['BCA', 'BNI', 'BRI', 'Mandiri', 'CIMB Niaga', 'Danamon', 'BTN']
PTKP_STATUSES = ['TK/0', 'TK/1', 'TK/2', 'K/0', 'K/1', 'K/2', 'K/3']
LEAVE_REASONS = [
    'Family event', 'Personal matters', 'Medical appointment',
    'Out of town', 'Home renovation', 'Religious ceremony'
]
EXPENSE_TITLES = [
    'Server hosting', 'Office supplies', 'Client lunch', 'Transport reimbursement',
    'Software license', 'Team building', 'Electricity bill', 'Internet bill'
]
COLLAB_MESSAGES = [
    'Can we schedule a sync meeting for this week?',
    'Updated the project requirements document.',
    'Please review the latest design changes.',
    'The client approved our proposal!',
    'Need assistance with the API integration.',
    'Quarterly report is ready for review.',
    'Deployment to staging completed successfully.',
]


def _random_date_in_range(start: date, end: date) -> date:
    """Returns a random date between start and end (inclusive)."""
    delta = (end - start).days
    if delta <= 0:
        return start
    return start + timedelta(days=random.randint(0, delta))


def _random_datetime_on_date(d: date, hour_min: int = 7, hour_max: int = 18) -> datetime:
    """Returns a random datetime on a given date within work hours."""
    hour = random.randint(hour_min, hour_max)
    minute = random.randint(0, 59)
    return datetime.combine(d, time(hour, minute))


def _is_workday(d: date) -> bool:
    """Returns True if the date is a weekday (Mon-Fri)."""
    return d.weekday() < 5


def _workdays_in_range(start: date, end: date) -> list:
    """Returns all workdays between start and end."""
    days = []
    current = start
    while current <= end:
        if _is_workday(current):
            days.append(current)
        current += timedelta(days=1)
    return days


def _offset_coords(lat: float, lng: float, distance_meters: float) -> tuple:
    """
    Offset lat/lng by approximately distance_meters in a random direction.
    Uses simple approximation (1 degree lat ~ 111km).

    Args:
        lat: Base latitude.
        lng: Base longitude.
        distance_meters: Distance to offset in meters.

    Returns:
        Tuple of (new_lat, new_lng).
    """
    angle = random.uniform(0, 2 * math.pi)
    dlat = (distance_meters / 111320) * math.cos(angle)
    dlng = (distance_meters / (111320 * math.cos(math.radians(lat)))) * math.sin(angle)
    return round(lat + dlat, 6), round(lng + dlng, 6)


class DummyDataService:
    """
    Generates and manages dummy/test data for all modules.
    All generated records are tagged with DUMMY_CREATOR_ID for easy cleanup.
    """

    @staticmethod
    def generate_all(date_from: date, date_to: date) -> dict:
        """
        Orchestrator: generates all dummy data in dependency order.
        Each step is wrapped individually so failures in one module
        don't block the rest.

        Args:
            date_from: Start date for time-series data (attendance, leaves, etc.).
            date_to: End date for time-series data.

        Returns:
            dict: Summary of generated record counts.
        """
        #logger.info(f"Generating dummy data from {date_from} to {date_to}")
        from app.modules.hris.models.payroll import PayrollBatch, PayrollBatchItem

        summary = {}
        errors = []

        def _safe_run(label, fn, *args, **kwargs):
            """Run a generator step; on failure, log and continue."""
            try:
                # Use a nested transaction (SAVEPOINT) so a failure in one
                # step doesn't roll back the parent transaction and erase
                # previously flushed dependencies like contacts.
                with db.session.begin_nested():
                    result = fn(*args, **kwargs)
                return result
            except Exception as e:
                logger.warning(f"Dummy data step '{label}' failed: {e}")
                errors.append(f"{label}: {str(e)[:120]}")
                return None

        # 1. Foundation data
        contacts = _safe_run('contacts', DummyDataService._generate_contacts) or []
        summary['contacts'] = len(contacts)

        result = _safe_run('employees', DummyDataService._generate_employees_and_users)
        employees, users = result if result else ([], [])
        summary['employees'] = len(employees)
        summary['users'] = len(users)

        # 2. HRIS data
        schedules = _safe_run('schedules', DummyDataService._generate_schedules, employees, date_from, date_to) or []
        summary['schedules'] = len(schedules)

        attendance_count = _safe_run('attendance', DummyDataService._generate_attendance, employees, date_from, date_to) or 0
        summary['attendance'] = attendance_count

        leaves = _safe_run('leaves', DummyDataService._generate_leaves, employees, date_from, date_to) or []
        summary['leaves'] = len(leaves)

        reimbursements = _safe_run('reimbursements', DummyDataService._generate_reimbursements, employees) or []
        summary['reimbursements'] = len(reimbursements)

        # 3. CRM data
        leads = _safe_run('leads', DummyDataService._generate_leads, contacts, users, date_from, date_to) or []
        summary['leads'] = len(leads)

        activities = _safe_run('activities', DummyDataService._generate_activities, leads, date_from, date_to) or []
        summary['activities'] = len(activities)

        tickets = _safe_run('tickets', DummyDataService._generate_tickets, contacts, users, date_from, date_to) or []
        summary['tickets'] = len(tickets)

        # 4. ERP data
        projects = _safe_run('projects', DummyDataService._generate_projects, contacts, users, employees, date_from, date_to) or []
        summary['projects'] = len(projects)

        invoices = _safe_run('invoices', DummyDataService._generate_invoices, projects, contacts, users, date_from, date_to) or []
        summary['invoices'] = len(invoices)

        expenses = _safe_run('expenses', DummyDataService._generate_expenses, projects, users, date_from, date_to) or []
        summary['expenses'] = len(expenses)

        tasks = _safe_run('tasks', DummyDataService._generate_tasks, projects, users) or []
        summary['tasks'] = len(tasks)

        # 5. Payroll (past months only — leave current month empty for manual test)
        batch_count_before = PayrollBatch.query.filter_by(created_by=DUMMY_CREATOR_ID).count()
        batch_item_count_before = PayrollBatchItem.query.filter_by(created_by=DUMMY_CREATOR_ID).count()
        payroll_count = _safe_run('payroll', DummyDataService._generate_payroll, employees, date_from, date_to) or 0
        batch_count_after = PayrollBatch.query.filter_by(created_by=DUMMY_CREATOR_ID).count()
        batch_item_count_after = PayrollBatchItem.query.filter_by(created_by=DUMMY_CREATOR_ID).count()

        summary['payroll_snapshots'] = payroll_count
        summary['payroll_batches'] = max(0, batch_count_after - batch_count_before)
        summary['payroll_batch_items'] = max(0, batch_item_count_after - batch_item_count_before)

        # 6. Collaboration (small sample)
        collab_count = _safe_run('collaboration', DummyDataService._generate_collaboration, users) or 0
        summary['collaboration_messages'] = collab_count

        try:
            db.session.commit()
        except IntegrityError as e:
            db.session.rollback()
            logger.warning(f"Final commit had IntegrityError (partial data saved): {e}")
            errors.append(f"final_commit: {str(e)[:120]}")

        if errors:
            summary['warnings'] = errors
            logger.warning(f"Dummy data completed with warnings: {errors}")
        
        #logger.info(f"Dummy data generation complete: {summary}")
        return summary

    @staticmethod
    def _generate_contacts() -> list:
        """Generate 15-25 random CRM contacts."""
        count = random.randint(15, 25)
        contacts = []
        categories = Category.query.filter_by(module='crm').all()

        for i in range(count):
            name = f"{random.choice(FIRST_NAMES)} {random.choice(LAST_NAMES)}"
            company = random.choice(COMPANY_NAMES)
            contact = Contact(
                name=name,
                company=company,
                email=f"{name.lower().replace(' ', '.')}{random.randint(100, 999)}@{company.lower().replace(' ', '').replace('pt', '').strip()}.co.id",
                phone=f"08{random.randint(1000000000, 9999999999)}",
                category_id=random.choice(categories).id if categories else None,
                created_by=DUMMY_CREATOR_ID
            )
            db.session.add(contact)
            contacts.append(contact)

        db.session.flush()
        return contacts

    @staticmethod
    def _generate_employees_and_users() -> tuple:
        """Generate 10-15 employees with linked user accounts."""
        count = random.randint(10, 15)
        employees = []
        users = []

        # Get required references
        user_role = Role.query.filter_by(name='User').first()
        offices = Office.query.all()
        from app.modules.hris.models import Shift
        shifts = Shift.query.all()
        emp_status = Status.query.filter_by(slug='emp_active').first()
        categories = Category.query.filter_by(module='hris').all()

        if not emp_status:
            emp_status = Status.query.filter_by(module='core', system_tag='ACTIVE').first()

        used_names = set()
        for i in range(count):
            # Ensure unique names
            while True:
                fname = random.choice(FIRST_NAMES)
                lname = random.choice(LAST_NAMES)
                full = f"{fname} {lname}"
                if full not in used_names:
                    used_names.add(full)
                    break

            unique_suffix = str(uuid6.uuid7())[:8]
            email = f"{fname.lower()}.{lname.lower()}.{unique_suffix}@aksara.dev"

            # Create User
            user = User(
                email=email,
                username=f"{fname.lower()[:3]}{lname.lower()[:3]}{unique_suffix}",
                role=user_role,
                created_by=DUMMY_CREATOR_ID
            )
            user.set_password('dummypass123')
            db.session.add(user)
            db.session.flush()
            users.append(user)

            # Random salary range (4M - 15M IDR)
            base_salary = random.randint(4000000, 15000000)
            # Round to nearest 500k
            base_salary = round(base_salary / 500000) * 500000

            office = random.choice(offices) if offices else None
            shift = random.choice(shifts) if shifts else None
            is_remote = random.random() < 0.15  # 15% remote workers

            employee = Employee(
                full_name=full,
                nip=f"NIP-{random.randint(10000, 99999)}",
                user_id=user.id,
                office_id=office.id if office and not is_remote else None,
                is_remote_allowed=is_remote,
                shift_id=shift.id if shift else None,
                category_id=random.choice(categories).id if categories else None,
                status_id=emp_status.id if emp_status else None,
                department=random.choice(DEPARTMENTS),
                position=random.choice(POSITIONS),
                join_date=_random_date_in_range(date(2023, 1, 1), date(2025, 6, 1)),
                base_salary=float(base_salary),
                salary_type=random.choice(['monthly'] * 8 + ['daily'] * 2),  # 80% monthly
                ptkp_status=random.choice(PTKP_STATUSES),
                bank_name=random.choice(BANKS),
                bank_account_number=str(random.randint(1000000000, 9999999999)),
                annual_leave_balance=random.randint(8, 15),
                reimbursement_limit=float(random.choice([3000000, 5000000, 7500000])),
                email=email,
                phone=f"08{random.randint(1000000000, 9999999999)}",
                created_by=DUMMY_CREATOR_ID
            )
            db.session.add(employee)
            employees.append(employee)

        db.session.flush()
        return employees, users

    @staticmethod
    def _generate_schedules(employees: list, date_from: date, date_to: date) -> list:
        """Generate shift schedules for employees across the date range."""
        from app.modules.hris.models import Shift, EmployeeSchedule
        shifts = Shift.query.all()
        if not shifts:
            return []

        schedules = []
        workdays = _workdays_in_range(date_from, date_to)

        for emp in employees:
            if emp.is_remote_allowed:
                continue  # Remote workers may not have strict schedules
            assigned_shift = emp.shift or random.choice(shifts)
            for d in workdays:
                # Random skip — not everyone has schedules for every day
                if random.random() < 0.05:  # 5% chance of no schedule
                    continue
                sched = EmployeeSchedule(
                    employee_id=emp.id,
                    shift_id=assigned_shift.id,
                    date=d,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(sched)
                schedules.append(sched)

        db.session.flush()
        return schedules

    @staticmethod
    def _generate_attendance(employees: list, date_from: date, date_to: date) -> int:
        """
        Generate attendance records with realistic geolocation patterns.
        ~70% within radius, ~20% near boundary, ~10% outside (simulates hacked client).
        """
        from app.modules.hris.models import Attendance
        offices = {o.id: o for o in Office.query.all()}
        attn_onwork = Status.query.filter_by(slug='attn_onwork').first()
        attn_late = Status.query.filter_by(slug='attn_late').first()
        attn_present = Status.query.filter_by(slug='attn_present').first()

        workdays = _workdays_in_range(date_from, date_to)
        count = 0

        for emp in employees:
            # Random attendance rate per employee (70% - 95%)
            attendance_rate = random.uniform(0.70, 0.95)
            office = offices.get(emp.office_id)

            for d in workdays:
                if random.random() > attendance_rate:
                    continue  # Absent this day

                # Random check-in time (7:30 - 10:00)
                check_in_hour = random.choices([7, 8, 8, 8, 9, 9, 10], k=1)[0]
                check_in_min = random.randint(0, 59)
                check_in = datetime.combine(d, time(check_in_hour, check_in_min))

                # Random check-out time (16:00 - 19:30)
                check_out_hour = random.choices([16, 17, 17, 17, 18, 18, 19], k=1)[0]
                check_out_min = random.randint(0, 59)
                check_out = datetime.combine(d, time(check_out_hour, check_out_min))

                # Determine status — late if check-in after 9:15
                is_late = check_in_hour > 9 or (check_in_hour == 9 and check_in_min > 15)
                status = attn_late if is_late else attn_present
                if not status:
                    status = attn_onwork

                # Geolocation with boundary testing
                lat, lng = None, None
                if office and office.latitude and office.longitude:
                    radius = office.radius_meters or 100
                    geo_type = random.random()
                    if geo_type < 0.70:
                        # Within radius (normal)
                        dist = random.uniform(0, radius * 0.8)
                    elif geo_type < 0.90:
                        # Near boundary (~90-110% of radius)
                        dist = random.uniform(radius * 0.9, radius * 1.1)
                    else:
                        # Outside (simulated hacked client)
                        dist = random.uniform(radius * 1.5, radius * 5)

                    lat, lng = _offset_coords(
                        float(office.latitude), float(office.longitude), dist
                    )

                late_reason = None
                if is_late:
                    late_reason = random.choice([
                        'Traffic jam', 'Family emergency', 'Public transport delay',
                        'Overslept', 'Medical appointment', 'Vehicle breakdown'
                    ])

                attn = Attendance(
                    employee_id=emp.id,
                    date=d,
                    check_in=check_in,
                    check_out=check_out,
                    status_id=status.id if status else None,
                    location_lat=str(lat) if lat else None,
                    location_long=str(lng) if lng else None,
                    late_reason=late_reason,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(attn)
                count += 1

        db.session.flush()
        return count

    @staticmethod
    def _generate_leaves(employees: list, date_from: date, date_to: date) -> list:
        """Generate random leave requests (0-4 per employee)."""
        from app.modules.hris.models import Leave
        leave_types = Status.query.filter(Status.module == 'hris', Status.sub_module == 'leave_type').all()
        leave_statuses = Status.query.filter(Status.module == 'hris', Status.sub_module == 'leave').all()
        leaves = []

        for emp in employees:
            leave_count = random.randint(0, 4)  # Truly random per employee
            for _ in range(leave_count):
                start = _random_date_in_range(date_from, date_to)
                duration = random.randint(1, 3)
                end = start + timedelta(days=duration)

                leave = Leave(
                    employee_id=emp.id,
                    leave_type_id=random.choice(leave_types).id if leave_types else None,
                    start_date=start,
                    end_date=end,
                    reason=random.choice(LEAVE_REASONS),
                    status_id=random.choice(leave_statuses).id if leave_statuses else None,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(leave)
                leaves.append(leave)

        db.session.flush()
        return leaves

    @staticmethod
    def _generate_reimbursements(employees: list) -> list:
        """Generate random reimbursements (0-3 per employee)."""
        from app.modules.hris.models import Reimbursement
        reimb_statuses = Status.query.filter(
            Status.module == 'hris', Status.sub_module == 'reimbursement'
        ).all()
        reimbursements = []

        for emp in employees:
            reimb_count = random.randint(0, 3)
            for _ in range(reimb_count):
                amount = random.randint(50000, 2000000)
                amount = round(amount / 10000) * 10000  # Round to 10k

                reimb = Reimbursement(
                    employee_id=emp.id,
                    title=random.choice(EXPENSE_TITLES),
                    amount=float(amount),
                    date=_random_date_in_range(date.today() - timedelta(days=60), date.today()),
                    description=f"Dummy reimbursement for testing purposes",
                    status_id=random.choice(reimb_statuses).id if reimb_statuses else None,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(reimb)
                reimbursements.append(reimb)

        db.session.flush()
        return reimbursements

    @staticmethod
    def _generate_leads(contacts: list, users: list, date_from: date, date_to: date) -> list:
        """Generate 15-25 CRM leads with random pipeline stages."""
        from app.modules.crm.models import Lead
        count = random.randint(15, 25)
        lead_statuses = Status.query.filter(
            Status.module == 'crm', Status.sub_module.in_(['leads', None])
        ).all()
        leads = []

        for i in range(count):
            contact = random.choice(contacts) if contacts else None
            lead = Lead(
                title=random.choice(LEAD_TITLES) + f" #{random.randint(100, 999)}",
                contact_id=contact.id if contact else None,
                status_id=random.choice(lead_statuses).id if lead_statuses else None,
                estimated_value=float(random.randint(5, 500) * 1000000),
                confidence_level=random.randint(10, 95),
                created_by=DUMMY_CREATOR_ID
            )
            
            # Randomize created_at backward in the date range
            rand_dt = _random_datetime_on_date(_random_date_in_range(date_from, date_to))
            lead.created_at = rand_dt
            lead.updated_at = rand_dt
            # Random assignees (1-2 from available users)
            if users:
                assignee_count = random.randint(1, min(2, len(users)))
                lead.assignees = random.sample(users, assignee_count)

            db.session.add(lead)
            leads.append(lead)

        db.session.flush()
        return leads

    @staticmethod
    def _generate_activities(leads: list, date_from: date, date_to: date) -> list:
        """Generate 1-5 random activities per lead."""
        from app.modules.crm.models import Activity
        activity_types = ['call', 'meeting', 'email', 'follow_up', 'presentation']
        activities = []

        for lead in leads:
            act_count = random.randint(1, 5)  # Random per lead
            for _ in range(act_count):
                act = Activity(
                    lead_id=lead.id,
                    type=random.choice(activity_types),
                    summary=f"{random.choice(activity_types).title()} with {lead.title[:20]}",
                    description=f"Follow-up activity for lead engagement",
                    date=_random_date_in_range(date_from, date_to),
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(act)
                activities.append(act)

        db.session.flush()
        return activities

    @staticmethod
    def _generate_tickets(contacts: list, users: list, date_from: date, date_to: date) -> list:
        """Generate 5-15 support tickets."""
        from app.modules.crm.models import Ticket
        count = random.randint(5, 15)
        ticket_statuses = Status.query.filter(
            Status.module == 'crm', Status.sub_module.in_(['tickets', None])
        ).all()
        tickets = []

        for i in range(count):
            contact = random.choice(contacts) if contacts else None
            ticket = Ticket(
                subject=random.choice(TICKET_SUBJECTS),
                description=f"Test ticket for QA validation #{random.randint(1000, 9999)}",
                contact_id=contact.id if contact else None,
                status_id=random.choice(ticket_statuses).id if ticket_statuses else None,
                created_by=DUMMY_CREATOR_ID
            )
            
            # Randomize created_at
            rand_dt = _random_datetime_on_date(_random_date_in_range(date_from, date_to))
            ticket.created_at = rand_dt
            ticket.updated_at = rand_dt
            
            # Random assignees (80% chance to be assigned)
            if users and random.random() > 0.2:
                assignee_count = random.randint(1, min(2, len(users)))
                ticket.assignees = random.sample(users, assignee_count)
            
            db.session.add(ticket)
            tickets.append(ticket)
            
        db.session.flush()
        return tickets

    @staticmethod
    def _generate_projects(contacts: list, users: list, employees: list,
                           date_from: date, date_to: date) -> list:
        """Generate 3-8 ERP projects (mix standalone + recurring)."""
        from app.modules.erp.models.core import Project, ResourceAllocation
        count = random.randint(3, 8)
        proj_statuses = Status.query.filter(
            Status.module == 'erp', Status.sub_module.in_(['projects', None])
        ).all()
        projects = []

        for i in range(count):
            is_recurring = random.random() < 0.3  # 30% recurring
            budget = float(random.randint(10, 500) * 1000000)
            contact = random.choice(contacts) if contacts else None
            pm = random.choice(users) if users else None

            start = _random_date_in_range(date_from, date_to)
            end = start + timedelta(days=random.randint(30, 180))
            # 50% chance to explicitly push end date past the generation window (simulating ongoing projects)
            if random.random() < 0.5:
                end = max(end, date_to + timedelta(days=random.randint(15, 90)))

            project = Project(
                title=random.choice(PROJECT_TITLES) + f" {random.randint(1, 99):02d}",
                description=f"Auto-generated project for testing #{random.randint(100, 999)}",
                status_id=random.choice(proj_statuses).id if proj_statuses else None,
                pm_id=pm.id if pm else None,
                contact_id=contact.id if contact else None,
                budget=budget,
                start_date=start,
                end_date=end,
                project_type='recurring' if is_recurring else 'standalone',
                billing_cycle='monthly' if is_recurring else None,
                recurring_amount=budget / 12 if is_recurring else 0.0,
                next_invoice_date=start + timedelta(days=30) if is_recurring else None,
                created_by=DUMMY_CREATOR_ID
            )
            db.session.add(project)
            db.session.flush()

            # Add random team allocations (1-3 employees)
            if employees:
                team_size = random.randint(1, min(3, len(employees)))
                team = random.sample(employees, team_size)
                for emp in team:
                    alloc = ResourceAllocation(
                        project_id=project.id,
                        employee_id=emp.id,
                        allocation_percentage=random.choice([50, 75, 100]),
                        start_date=start,
                        end_date=end,
                        created_by=DUMMY_CREATOR_ID
                    )
                    db.session.add(alloc)

            projects.append(project)

        db.session.flush()
        return projects

    @staticmethod
    def _generate_invoices(projects: list, contacts: list, users: list,
                           date_from: date, date_to: date) -> list:
        """Generate invoices across various payment states."""
        from app.modules.erp.models.core import Invoice, InvoicePayment
        inv_statuses = Status.query.filter(
            Status.module == 'erp', Status.sub_module.in_(['invoices', None])
        ).all()
        invoices = []

        if not users:
            fallback = User.query.filter_by(role_id=Role.query.filter_by(name='User').first().id if Role.query.filter_by(name='User').first() else None).first() or User.query.first()
            if fallback:
                users = [fallback]

        for proj in projects:
            # Probability for invoices: 25% for ongoing, 90% for completed/past projects
            is_completed = proj.end_date <= date_to
            if random.random() > (0.90 if is_completed else 0.25):
                continue
                
            # Restrict issue date to project bounds (up to date_to)
            max_issue = min(date_to, proj.end_date + timedelta(days=14))
            issue = _random_date_in_range(proj.start_date, max_issue)
            due = issue + timedelta(days=random.choice([14, 30, 45]))
            amount = float(random.randint(5, 200) * 1000000)

            # Random payment progress
            status = random.choice(inv_statuses) if inv_statuses else None
            paid_pct = random.choice([0, 0.25, 0.5, 0.75, 1.0])
            paid_amount = amount * paid_pct

            inv = Invoice(
                number=f"INV-{issue.strftime('%Y%m')}-{random.randint(10000, 99999)}",
                project_id=proj.id,
                contact_id=proj.contact_id or (random.choice(contacts).id if contacts else None),
                status_id=status.id if status else None,
                issue_date=issue,
                due_date=due,
                amount=amount,
                paid_amount=paid_amount,
                notes=f"Invoice for {proj.title}",
                created_by=DUMMY_CREATOR_ID
            )
            db.session.add(inv)
            db.session.flush()

            if paid_amount > 0:
                payment = InvoicePayment(
                    invoice_id=inv.id,
                    amount=paid_amount,
                    date=_random_date_in_range(issue, due),
                    notes="Initial dummy payment",
                    recorded_by_id=random.choice(users).id if users else None,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(payment)

            invoices.append(inv)

        db.session.flush()
        return invoices

    @staticmethod
    def _generate_expenses(projects: list, users: list,
                           date_from: date, date_to: date) -> list:
        """Generate random expenses linked to projects."""
        from app.modules.erp.models.core import Expense
        expenses = []

        category_slugs = [c.slug for c in Category.query.filter_by(module='erp_expense').all()]
        if not category_slugs:
            category_slugs = ['lainnya']

        if not users:
            fallback = User.query.filter_by(role_id=Role.query.filter_by(name='User').first().id if Role.query.filter_by(name='User').first() else None).first() or User.query.first()
            if fallback:
                users = [fallback]

        for proj in projects:
            exp_count = random.randint(0, 5)  # Random per project
            for _ in range(exp_count):
                amount = float(random.randint(50, 5000) * 1000)
                exp = Expense(
                    title=random.choice(EXPENSE_TITLES),
                    amount=amount,
                    date=_random_date_in_range(date_from, date_to),
                    description=f"Operational expense for {proj.title}",
                    category=random.choice(category_slugs),
                    project_id=proj.id,
                    user_id=random.choice(users).id if users else None,
                    source='manual',
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(exp)
                expenses.append(exp)

        db.session.flush()
        return expenses

    @staticmethod
    def _generate_tasks(projects: list, users: list) -> list:
        """Generate 3-8 tasks per project with random states."""
        from app.core.models.task import Task
        task_statuses = Status.query.filter(
            Status.module == 'erp', Status.sub_module.in_(['planner', None])
        ).all()
        tasks = []

        for proj in projects:
            task_count = random.randint(3, 8)  # Random per project
            for j in range(task_count):
                proj_duration = (proj.end_date - proj.start_date).days
                start_offset = random.randint(0, max(0, proj_duration - 5))
                start = proj.start_date + timedelta(days=start_offset)
                
                max_task_duration = min(21, (proj.end_date - start).days)
                end = start + timedelta(days=random.randint(1, max(1, max_task_duration)))

                # Fill time window for better timeline visual test coverage.
                start_hour = random.randint(7, 16)
                start_minute = random.choice([0, 15, 30, 45])
                duration_hours = random.randint(1, 8)
                duration_minutes = random.choice([0, 15, 30, 45])

                start_minutes_total = (start_hour * 60) + start_minute
                end_minutes_total = min((23 * 60) + 45, start_minutes_total + (duration_hours * 60) + duration_minutes)

                start_time_val = time(start_minutes_total // 60, start_minutes_total % 60)
                end_time_val = time(end_minutes_total // 60, end_minutes_total % 60)

                # Guarantee a visible duration even on edge random picks.
                if end_time_val <= start_time_val:
                    safe_end_minutes = min((23 * 60) + 45, start_minutes_total + 30)
                    end_time_val = time(safe_end_minutes // 60, safe_end_minutes % 60)

                task = Task(
                    title=f"Task {j + 1}: {random.choice(['Design', 'Develop', 'Test', 'Deploy', 'Review', 'Document', 'Configure', 'Integrate'])}",
                    description=f"Auto-generated task for {proj.title}",
                    entity_type='project',
                    entity_id=proj.id,
                    status_id=random.choice(task_statuses).id if task_statuses else None,
                    start_date=start,
                    end_date=end,
                    start_time=start_time_val,
                    end_time=end_time_val,
                    progress=random.randint(0, 100),
                    created_by=DUMMY_CREATOR_ID
                )

                # Random assignee
                if users and random.random() > 0.1:  # 90% assigned
                    task.assignees.append(random.choice(users))

                db.session.add(task)
                tasks.append(task)

        db.session.flush()
        return tasks

    @staticmethod
    def _generate_payroll(employees: list, date_from: date, date_to: date) -> int:
        """
        Generate payroll snapshots for past complete months.
        Current month is LEFT EMPTY for manual testing.
        Uses real PayrollService for accurate calculations.
        """
        from app.modules.hris.services_payroll import PayrollService
        from app.modules.hris.models.payroll import PayrollSnapshot, PayrollBatch, PayrollBatchItem, Payslip, PayslipItem
        from app.modules.hris.models.master import SalaryComponent
        from app.cli import DEFAULT_PAYROLL_COMPONENTS

        # Keep dummy payroll generation aligned with active payroll seed defaults.
        # This avoids stale schema/data coupling from old local databases.
        by_name = {c.name: c for c in SalaryComponent.query.filter(SalaryComponent.deleted_at.is_(None)).all()}
        for payload in DEFAULT_PAYROLL_COMPONENTS:
            component = by_name.get(payload['name'])
            if not component:
                component = SalaryComponent(**payload, created_by=DUMMY_CREATOR_ID)
                db.session.add(component)
                by_name[payload['name']] = component
            else:
                component.type = payload['type']
                component.calculation_type = payload['calculation_type']
                component.default_amount = payload['default_amount']
                component.is_mandatory = payload['is_mandatory']
                component.is_taxable = payload['is_taxable']

            if component.type == 'addition':
                component.type = 'earning'

        db.session.flush()

        today = date.today()
        snapshot_count = 0
        batch_count = 0
        batch_item_count = 0

        ptkp_aliases = {
            'TK0': 'TK/0',
            'TK1': 'TK/1',
            'TK2': 'TK/2',
            'TK3': 'TK/3',
            'K0': 'K/0',
            'K1': 'K/1',
            'K2': 'K/2',
            'K3': 'K/3',
            'KI0': 'K/I/0',
            'KI1': 'K/I/1',
            'KI2': 'K/I/2',
            'KI3': 'K/I/3'
        }

        # Normalize missing/legacy PTKP formats before payroll calculation.
        for emp in employees:
            normalized_ptkp = str(emp.ptkp_status or '').strip().upper()
            if not normalized_ptkp:
                emp.ptkp_status = random.choice(PTKP_STATUSES)
                continue

            compact = normalized_ptkp.replace('/', '')
            if compact in ptkp_aliases:
                emp.ptkp_status = ptkp_aliases[compact]

        requester_user_id = next((emp.user_id for emp in employees if getattr(emp, 'user_id', None)), None)
        if not requester_user_id:
            requester = User.query.filter_by(created_by=DUMMY_CREATOR_ID).first()
            requester_user_id = requester.id if requester else None

        # Generate month by month, but skip current month
        current = date_from.replace(day=1)
        while current < date_to:
            month_start = current
            # Last day of month
            if current.month == 12:
                month_end = date(current.year + 1, 1, 1) - timedelta(days=1)
            else:
                month_end = date(current.year, current.month + 1, 1) - timedelta(days=1)

            # Skip if this is the current month (leave empty for manual testing)
            if current.year == today.year and current.month == today.month:
                if current.month == 12:
                    current = date(current.year + 1, 1, 1)
                else:
                    current = date(current.year, current.month + 1, 1)
                continue

            # Skip if month is after date_to
            if month_start > date_to:
                break

            month_end = min(month_end, date_to)

            # Check for existing snapshot overlap
            existing = PayrollSnapshot.query.filter(
                (PayrollSnapshot.period_start <= month_end) &
                (PayrollSnapshot.period_end >= month_start)
            ).first()
            if existing:
                if current.month == 12:
                    current = date(current.year + 1, 1, 1)
                else:
                    current = date(current.year, current.month + 1, 1)
                continue

            # Create snapshot
            fake_time = _random_datetime_on_date(month_end)
            status_draft = Status.query.filter_by(module='hris', slug='payslip_draft').first()
            if not status_draft:
                status_draft = Status.query.filter_by(module='hris', system_tag='NEW').first()

            snapshot = PayrollSnapshot(
                period_start=month_start,
                period_end=month_end,
                status_id=status_draft.id if status_draft else None,
                run_type='default',
                notes='Generated by DummyDataService',
                created_by=DUMMY_CREATOR_ID,
                created_at=fake_time,
                updated_at=fake_time
            )
            db.session.add(snapshot)
            db.session.flush()

            batch = None
            if requester_user_id:
                batch = PayrollBatch(
                    snapshot_id=snapshot.id,
                    requested_by_id=requester_user_id,
                    run_type='default',
                    status='completed',
                    period_start=month_start,
                    period_end=month_end,
                    total_employees=len(employees),
                    generated_count=0,
                    partial_count=0,
                    skipped_count=0,
                    notes='Generated by DummyDataService',
                    created_by=DUMMY_CREATOR_ID,
                    created_at=fake_time,
                    updated_at=fake_time
                )
                db.session.add(batch)
                db.session.flush()
                batch_count += 1
            else:
                logger.warning('Skipping dummy payroll batch creation because no requester user is available.')

            generated_count = 0
            skipped_count = 0

            for emp in employees:
                try:
                    payslip, items = PayrollService.generate_payslip(emp, month_start, month_end)
                    if payslip:
                        payslip.snapshot_id = snapshot.id
                        if batch:
                            payslip.source_batch_id = batch.id
                        payslip.created_by = DUMMY_CREATOR_ID
                        payslip.created_at = fake_time
                        payslip.updated_at = fake_time
                        db.session.add(payslip)
                        db.session.flush()

                        for item in items:
                            item.payslip_id = payslip.id
                            item.created_by = DUMMY_CREATOR_ID
                            item.created_at = fake_time
                            item.updated_at = fake_time
                            db.session.add(item)

                        generated_count += 1

                        if batch:
                            db.session.add(PayrollBatchItem(
                                batch_id=batch.id,
                                employee_id=emp.id,
                                requested_start=month_start,
                                requested_end=month_end,
                                covered_start=month_start,
                                covered_end=month_end,
                                decision='generated',
                                reason='dummy_generated',
                                existing_payslip_refs=None,
                                created_by=DUMMY_CREATOR_ID,
                                created_at=fake_time,
                                updated_at=fake_time
                            ))
                            batch_item_count += 1
                    else:
                        skipped_count += 1
                        if batch:
                            db.session.add(PayrollBatchItem(
                                batch_id=batch.id,
                                employee_id=emp.id,
                                requested_start=month_start,
                                requested_end=month_end,
                                covered_start=None,
                                covered_end=None,
                                decision='skipped',
                                reason='generator_returned_empty',
                                existing_payslip_refs=None,
                                created_by=DUMMY_CREATOR_ID,
                                created_at=fake_time,
                                updated_at=fake_time
                            ))
                            batch_item_count += 1
                except Exception as e:
                    logger.warning(f"Payroll generation failed for {emp.full_name}: {e}")
                    skipped_count += 1
                    if batch:
                        db.session.add(PayrollBatchItem(
                            batch_id=batch.id,
                            employee_id=emp.id,
                            requested_start=month_start,
                            requested_end=month_end,
                            covered_start=None,
                            covered_end=None,
                            decision='skipped',
                            reason='generator_exception',
                            existing_payslip_refs=None,
                            created_by=DUMMY_CREATOR_ID,
                            created_at=fake_time,
                            updated_at=fake_time
                        ))
                        batch_item_count += 1
                    continue

            if batch:
                batch.generated_count = generated_count
                batch.skipped_count = skipped_count
                batch.partial_count = 0

            snapshot_count += 1

            # Advance to next month
            if current.month == 12:
                current = date(current.year + 1, 1, 1)
            else:
                current = date(current.year, current.month + 1, 1)

        # Generate random On-Demand Payrolls for testing
        on_demand_count = random.randint(1, 3)
        for _ in range(on_demand_count):
            if not employees:
                break
            
            # Pick a random past date
            od_start = _random_date_in_range(date_from, max(date_from, date_to - timedelta(days=30)))
            od_end = min(date_to, od_start + timedelta(days=random.randint(5, 15)))

            # Pick 1-3 random employees
            od_employees = random.sample(employees, min(random.randint(1, 3), len(employees)))

            fake_time = _random_datetime_on_date(od_end)
            status_draft = Status.query.filter_by(module='hris', slug='payslip_draft').first()
            if not status_draft:
                status_draft = Status.query.filter_by(module='hris', system_tag='NEW').first()

            snapshot = PayrollSnapshot(
                period_start=od_start,
                period_end=od_end,
                status_id=status_draft.id if status_draft else None,
                run_type='on_demand',
                notes='Generated by DummyDataService (On-Demand)',
                created_by=DUMMY_CREATOR_ID,
                created_at=fake_time,
                updated_at=fake_time
            )
            db.session.add(snapshot)
            db.session.flush()

            batch = None
            if requester_user_id:
                batch = PayrollBatch(
                    snapshot_id=snapshot.id,
                    requested_by_id=requester_user_id,
                    run_type='on_demand',
                    status='completed',
                    period_start=od_start,
                    period_end=od_end,
                    total_employees=len(od_employees),
                    generated_count=0,
                    partial_count=0,
                    skipped_count=0,
                    notes='Generated by DummyDataService (On-Demand)',
                    created_by=DUMMY_CREATOR_ID,
                    created_at=fake_time,
                    updated_at=fake_time
                )
                db.session.add(batch)
                db.session.flush()
                batch_count += 1
            
            generated_count = 0
            skipped_count = 0

            for emp in od_employees:
                try:
                    payslip, items = PayrollService.generate_payslip(
                        emp, 
                        od_start, 
                        od_end, 
                        run_type='on_demand', 
                        source_batch_id=batch.id if batch else None,
                        reference_start=od_start,
                        reference_end=od_end
                    )
                    if payslip:
                        payslip.snapshot_id = snapshot.id
                        if batch:
                            payslip.source_batch_id = batch.id
                        payslip.created_by = DUMMY_CREATOR_ID
                        payslip.created_at = fake_time
                        payslip.updated_at = fake_time
                        db.session.add(payslip)
                        db.session.flush()

                        for item in items:
                            item.payslip_id = payslip.id
                            item.created_by = DUMMY_CREATOR_ID
                            item.created_at = fake_time
                            item.updated_at = fake_time
                            db.session.add(item)

                        generated_count += 1

                        if batch:
                            db.session.add(PayrollBatchItem(
                                batch_id=batch.id,
                                employee_id=emp.id,
                                requested_start=od_start,
                                requested_end=od_end,
                                covered_start=od_start,
                                covered_end=od_end,
                                decision='generated',
                                reason='dummy_generated_on_demand',
                                existing_payslip_refs=None,
                                created_by=DUMMY_CREATOR_ID,
                                created_at=fake_time,
                                updated_at=fake_time
                            ))
                            batch_item_count += 1
                    else:
                        skipped_count += 1
                        if batch:
                            db.session.add(PayrollBatchItem(
                                batch_id=batch.id,
                                employee_id=emp.id,
                                requested_start=od_start,
                                requested_end=od_end,
                                covered_start=None,
                                covered_end=None,
                                decision='skipped',
                                reason='generator_returned_empty',
                                existing_payslip_refs=None,
                                created_by=DUMMY_CREATOR_ID,
                                created_at=fake_time,
                                updated_at=fake_time
                            ))
                            batch_item_count += 1
                except Exception as e:
                    logger.warning(f"On-Demand Payroll generation failed for {emp.full_name}: {e}")
                    skipped_count += 1
                    if batch:
                        db.session.add(PayrollBatchItem(
                            batch_id=batch.id,
                            employee_id=emp.id,
                            requested_start=od_start,
                            requested_end=od_end,
                            covered_start=None,
                            covered_end=None,
                            decision='skipped',
                            reason='generator_exception',
                            existing_payslip_refs=None,
                            created_by=DUMMY_CREATOR_ID,
                            created_at=fake_time,
                            updated_at=fake_time
                        ))
                        batch_item_count += 1
                    continue

            if batch:
                batch.generated_count = generated_count
                batch.skipped_count = skipped_count
                batch.partial_count = 0

            snapshot_count += 1

        db.session.flush()
        return snapshot_count

    @staticmethod
    def _generate_collaboration(users: list) -> int:
        """Generate small sample of collaboration messages with notifications and Workspace notes."""
        from app.modules.collaboration.models import Message, Note
        from app.core.services.notification import NotificationService

        if not users:
            return 0

        # Generate Messages (Inbox)
        msg_count = random.randint(8, 15)
        subjects = [
            'Quick Sync', 'Project Update', 'Meeting Notes',
            'Task Follow-up', 'Weekly Summary', 'Urgent Approval Needed'
        ]

        if len(users) >= 2:
            for _ in range(msg_count):
                sender = random.choice(users)
                recipient = random.choice([u for u in users if u.id != sender.id])

                msg = Message(
                    sender_id=sender.id,
                    recipient_id=recipient.id,
                    subject=random.choice(subjects),
                    body=random.choice(COLLAB_MESSAGES),
                    is_read=random.choice([True, False]),
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(msg)

                try:
                    NotificationService.send(
                        recipient.id,
                        'New Message',
                        f'Message from {sender.username or sender.email}',
                        '/collab/inbox',
                        commit=False
                    )
                except Exception:
                    pass

        # Generate Notes (Workspace)
        for user in users:
            note_count = random.randint(2, 5)
            for _ in range(note_count):
                note = Note(
                    title=random.choice(['To-Do', 'Meeting Takeaways', 'Project Idea', '', 'Reminder']),
                    content=random.choice([
                        'Finish the weekly report and send to manager.',
                        'Review the new ERP module features.',
                        'Schedule a sync with the frontend team.',
                        'Need to approve pending reimbursements tomorrow.',
                        'Client presentation at 2 PM on Friday.'
                    ]),
                    color=random.choice(['warning', 'info', 'success', 'danger', 'primary']),
                    owner_id=user.id,
                    created_by=DUMMY_CREATOR_ID
                )
                db.session.add(note)

        db.session.flush()
        return msg_count

    @staticmethod
    def clear_all() -> dict:
        """
        Clears all dummy data created by this service.
        Preserves: seed data (Roles, Permissions, Statuses, Categories,
        Salary Components, TER Rates, Settings, Shifts, Admin user, Office).

        Returns:
            dict: Summary of deleted record counts.
        """
        #logger.info("Clearing all dummy data...")
        summary = {}

        try:
            # Delete in reverse dependency order with explicit WHERE clauses to catch any 
            # user-generated data that is attached to dummy parents, or association tables.
            cid = DUMMY_CREATOR_ID
            tables_to_clean = [
                # Payroll
                ('hris_payslip_item', 'PayslipItem', "payslip_id IN (SELECT id FROM hris_payslip WHERE employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid))"),
                ('hris_payslip', 'Payslip', "employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('hris_payroll_batch_item', 'PayrollBatchItem', "batch_id IN (SELECT id FROM hris_payroll_batch WHERE created_by = :cid) OR employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('hris_payroll_batch', 'PayrollBatch', "created_by = :cid OR requested_by_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                ('hris_payroll_snapshot', 'PayrollSnapshot', "created_by = :cid"),
                # HRIS
                ('hris_reimbursement', 'Reimbursement', "employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('hris_leave', 'Leave', "employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('hris_attendance', 'Attendance', "employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('hris_employee_schedule', 'EmployeeSchedule', "employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                # ERP
                ('erp_expense', 'Expense', "project_id IN (SELECT id FROM erp_project WHERE created_by = :cid) OR created_by = :cid"),
                ('erp_invoice_payment', 'InvoicePayment', "invoice_id IN (SELECT id FROM erp_invoice WHERE project_id IN (SELECT id FROM erp_project WHERE created_by = :cid)) OR created_by = :cid"),
                ('erp_invoice', 'Invoice', "project_id IN (SELECT id FROM erp_project WHERE created_by = :cid) OR created_by = :cid"),
                ('erp_resource_allocation', 'ResourceAllocation', "project_id IN (SELECT id FROM erp_project WHERE created_by = :cid) OR employee_id IN (SELECT id FROM core_employee WHERE created_by = :cid)"),
                ('erp_project', 'Project', "created_by = :cid"),
                
                # Assignees (Many-to-Many Association tables)
                ('core_task_assignees', 'TaskAssignees', "task_id IN (SELECT id FROM core_task WHERE created_by = :cid) OR user_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                ('crm_lead_assignees', 'LeadAssignees', "lead_id IN (SELECT id FROM crm_lead WHERE created_by = :cid) OR user_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                ('crm_ticket_assignees', 'TicketAssignees', "ticket_id IN (SELECT id FROM crm_ticket WHERE created_by = :cid) OR user_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                
                # Core Tasks
                ('core_task', 'Task', "created_by = :cid"),
                # CRM
                ('crm_activity', 'Activity', "lead_id IN (SELECT id FROM crm_lead WHERE created_by = :cid) OR created_by = :cid"),
                ('crm_ticket', 'Ticket', "created_by = :cid"),
                ('crm_lead', 'Lead', "created_by = :cid"),
                # Collaboration
                ('collab_note', 'Note', "owner_id IN (SELECT id FROM user WHERE created_by = :cid) OR created_by = :cid"),
                ('collab_message', 'Message', "sender_id IN (SELECT id FROM user WHERE created_by = :cid) OR recipient_id IN (SELECT id FROM user WHERE created_by = :cid) OR created_by = :cid"),
                # Notifications (dummy-related) MUST USE user_id criteria
                ('notification', 'Notification', "user_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                # Activity Log
                ('activity_log', 'ActivityLog', "user_id IN (SELECT id FROM user WHERE created_by = :cid)"),
                # Contacts
                ('core_contact', 'Contact', "created_by = :cid"),
                # Core
                ('core_employee', 'Employee', "created_by = :cid"),
                ('user', 'User', "created_by = :cid"),
            ]

            for table_name, model_name, where_clause in tables_to_clean:
                try:
                    count = db.session.execute(
                        db.text(f"DELETE FROM {table_name} WHERE {where_clause}"),
                        {'cid': cid}
                    ).rowcount
                    summary[model_name] = count
                except Exception as e:
                    logger.warning(f"Could not clean {table_name}: {e}")
                    summary[model_name] = f"error: {str(e.orig)[:150] if hasattr(e, 'orig') else str(e)[:150]}"

            # Insert a clear_all Audit Log message to maintain the trail
            from app.core.models.audit import AuditLog
            from app.core.services.audit import get_user_id
            reset_log = AuditLog(
                entity_type='System',
                entity_id='0',
                action='SYSTEM_RESET',
                new_value='{"message": "Dummy data cleared and reset for staging environment."}',
                created_by=get_user_id() or DUMMY_CREATOR_ID
            )
            db.session.add(reset_log)

            db.session.commit()
            #logger.info(f"Dummy data cleared: {summary}")
            return summary

        except Exception as e:
            db.session.rollback()
            logger.error(f"Clear dummy data failed: {e}")
            raise
