#!/usr/bin/env python3
"""
Delete the single most recently created appointment (by created_at, then id)
and all related rows + upload files. Reverts doctor balance/totals for linked
DoctorTransaction rows before deleting them.

Usage (from project root):
  python scripts/delete_latest_appointment.py
"""
from __future__ import annotations

import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

from app import create_app, db  # noqa: E402
from app.models import (  # noqa: E402
    Appointment,
    DoctorTransaction,
    MedicalDocument,
    MedicalHistory,
    PlatformRevenue,
    Prescription,
    Refund,
    RefundPayoutDetail,
    Review,
    VideoCallRecording,
)
from app.utils.file_upload import delete_uploaded_file  # noqa: E402


def _resolve_upload_path(app, relative_path: str) -> str:
    if not relative_path:
        return ""
    rel = relative_path.replace("\\", "/").lstrip("/")
    base = app.config.get("UPLOAD_FOLDER", os.path.join(ROOT, "app", "static", "uploads"))
    return os.path.normpath(os.path.join(base, rel))


def _unlink_if_exists(path: str) -> None:
    if path and os.path.isfile(path):
        try:
            os.remove(path)
            print(f"  removed file: {path}")
        except OSError as e:
            print(f"  (warn) could not remove file {path}: {e}")


def revert_doctor_transactions(appointment: Appointment) -> None:
    doctor = appointment.doctor
    txs = DoctorTransaction.query.filter_by(appointment_id=appointment.id).all()
    for tx in txs:
        if tx.transaction_type == "earning" and tx.amount:
            doctor.balance = (doctor.balance or 0) - float(tx.amount)
            doctor.total_earned = (doctor.total_earned or 0) - float(tx.amount)
        elif tx.transaction_type == "penalty" and tx.amount is not None:
            doctor.balance = (doctor.balance or 0) - float(tx.amount)
            doctor.total_penalties = (doctor.total_penalties or 0) + float(tx.amount)


def main():
    app = create_app()
    with app.app_context():
        appt = (
            Appointment.query.order_by(Appointment.created_at.desc(), Appointment.id.desc()).first()
        )
        if not appt:
            print("No appointments found.")
            return

        aid = appt.id
        print(
            f"Deleting appointment id={aid} "
            f"(created_at={appt.created_at}, patient_id={appt.patient_id}, doctor_id={appt.doctor_id})"
        )

        try:
            ps = appt.payment_screenshot
            if ps and not str(ps).startswith("safepay_"):
                delete_uploaded_file(ps)

            VideoCallRecording.query.filter_by(appointment_id=aid).delete(synchronize_session=False)

            for ref in Refund.query.filter_by(appointment_id=aid).all():
                RefundPayoutDetail.query.filter_by(refund_id=ref.id).delete(synchronize_session=False)
                db.session.delete(ref)

            PlatformRevenue.query.filter_by(appointment_id=aid).delete(synchronize_session=False)

            revert_doctor_transactions(appt)
            DoctorTransaction.query.filter_by(appointment_id=aid).delete(synchronize_session=False)

            rev = Review.query.filter_by(appointment_id=aid).first()
            if rev:
                db.session.delete(rev)

            presc = Prescription.query.filter_by(appointment_id=aid).first()
            if presc:
                if presc.pdf_path:
                    rel = str(presc.pdf_path).replace("\\", "/")
                    if "static/uploads/" in rel:
                        rel = rel.split("static/uploads/", 1)[-1]
                    rel = rel.lstrip("/")
                    delete_uploaded_file(rel)
                db.session.delete(presc)

            mh = MedicalHistory.query.filter_by(appointment_id=aid).first()
            if mh:
                db.session.delete(mh)

            for doc in MedicalDocument.query.filter_by(appointment_id=aid).all():
                if doc.file_path:
                    full = _resolve_upload_path(app, doc.file_path)
                    _unlink_if_exists(full)
                db.session.delete(doc)

            db.session.delete(appt)
            db.session.commit()
            print("Done. Appointment and related data removed.")
        except Exception:
            db.session.rollback()
            raise


if __name__ == "__main__":
    main()
