from django.core.management.base import BaseCommand
from django.db import connection


class Command(BaseCommand):
    help = "Wipe all dev data: complaints, observations, appreciation, feedback, staff, departments, sections, patients, integrations"

    def add_arguments(self, parser):
        parser.add_argument("--confirm", action="store_true", help="Confirm data wipe")
        parser.add_argument("--keep-org", action="store_true", help="Keep hospitals, departments, sections, staff")

    def handle(self, *args, **options):
        if not options["confirm"]:
            self.stdout.write(self.style.ERROR("Add --confirm to confirm data wipe"))
            return

        keep_org = options.get("keep_org", False)

        truncate_order = [
            "complaints_complaintupdate",
            "complaints_complaintattachment",
            "complaints_complaintinvolvedstaff",
            "complaints_complaintinvolveddepartment",
            "complaints_complaintadverseaction_involved_staff",
            "complaints_complaintadverseaction",
            "complaints_complaintadverseactionattachment",
            "complaints_complaintcommunication",
            "complaints_complaintexplanation",
            "complaints_explanationattachment",
            "complaints_complaintmeeting",
            "complaints_complaintprinteraction",
            "complaints_departmentmanagerreview",
            "complaints_managerreviewanswer",
            "complaints_complaint",
            "complaints_inquiryattachment",
            "complaints_inquiryexplanation",
            "complaints_inquiryexplanationattachment",
            "complaints_inquiryupdate",
            "complaints_inquiry",
            "complaints_governmentticket",
            "complaints_patientcomplaintsession",
            "complaints_oncalladminschedule",
            "complaints_oncalladmin",
            "observations_observationattachment",
            "observations_observationnote",
            "observations_observationstatuslog",
            "observations_observation",
            "appreciation_userbadge",
            "appreciation_appreciationbadge",
            "appreciation_appreciationstats",
            "appreciation_appreciation",
            "feedback_feedbackattachment",
            "feedback_feedbackresponse",
            "feedback_commentactionplan",
            "feedback_commentimport",
            "feedback_patientcomment",
            "feedback_feedback",
            "dashboard_complaintrequest",
            "dashboard_escalatedcomplaintlog",
            "dashboard_evaluationnote",
            "dashboard_inquirydetail",
            "dashboard_reportcompletion",
            "analytics_kpivalue",
            "analytics_kpireportdepartmentbreakdown",
            "analytics_kpireportlocationbreakdown",
            "analytics_kpireportmonthlydata",
            "analytics_kpireportsourcebreakdown",
            "analytics_kpireport",
            "analytics_kpi",
            "surveys_surveyinstance",
            "physicians_physicianindividualrating",
            "physicians_physicianmonthlyrating",
            "rca_rcaattachment",
            "rca_rcacorrectiveaction",
            "rca_rcanote",
            "rca_rcarootcause",
            "rca_rcastatuslog",
            "rca_rootcauseanalysis",
            "projects_qiproject_related_actions",
            "projects_qiproject_team_members",
            "projects_qiprojecttask",
            "projects_pdcaphase",
            "projects_focusphase",
            "projects_qiproject",
            "organizations_staffsubsection",
            "organizations_staffsection",
            "organizations_staff",
            "organizations_section",
            "organizations_department",
            "organizations_legacyhierarchymapping",
            "organizations_subsection",
            "organizations_mainsection",
            "organizations_location",
            "organizations_patient",
            "integrations_hispatientvisit",
            "integrations_histestpatient",
            "integrations_histestvisit",
        ]

        org_tables = {
            "organizations_staff",
            "organizations_staffsection",
            "organizations_staffsubsection",
            "organizations_section",
            "organizations_department",
        }

        with connection.cursor() as cursor:
            for table in truncate_order:
                if keep_org and table in org_tables:
                    self.stdout.write(f"  SKIP (keep-org): {table}")
                    continue
            for table in truncate_order:
                try:
                    cursor.execute(f'TRUNCATE TABLE "{table}" CASCADE')
                    self.stdout.write(f"  Truncated: {table}")
                except Exception as e:
                    self.stdout.write(self.style.WARNING(f"  SKIP {table}: {e}"))

            cursor.execute("UPDATE accounts_user SET department_id = NULL")
            self.stdout.write("  Nullified: accounts_user.department_id")

        self.stdout.write(self.style.SUCCESS("\nDone. All dev data wiped."))
