from flask import Blueprint, request, jsonify, send_from_directory
from flask_jwt_extended import jwt_required
from db.db import get_db_connection
from config.auth import role_required  # ✅ imported properly now
import mysql.connector


patient_history_bp = Blueprint('patient_history', __name__)



@patient_history_bp.route('/present_complaints', methods=['POST'])
@jwt_required()
@role_required('doctor')
def add_present_complaint():
    """Add a new Present Complaint tag"""
    data = request.get_json() or {}
    name = (data.get('name') or "").strip()
    if not name:
        return jsonify({'error': 'Missing name'}), 400

    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'DB connection failed'}), 500

    cursor = conn.cursor()
    try:
        cursor.execute("INSERT INTO complaint_tags (name) VALUES (%s)", (name,))
        conn.commit()
        return jsonify({'message': 'saved', 'id': cursor.lastrowid, 'name': name}), 200
    except mysql.connector.IntegrityError:
        conn.rollback()
        cursor.execute("SELECT id FROM complaint_tags WHERE name=%s", (name,))
        row = cursor.fetchone()
        return jsonify({'message': 'already_exists', 'id': row[0] if row else None, 'name': name}), 200
    except Exception as e:
        print("Error saving complaint tag:", e)
        conn.rollback()
        return jsonify({'error': str(e)}), 500
    finally:
        cursor.close()
        conn.close()


@patient_history_bp.route('/present_complaints', methods=['GET'])
@jwt_required()
@role_required('doctor')
def search_present_complaints():
    """Search complaint tags with flexible matching"""
    q = request.args.get('q', '').strip().lower()

    conn = get_db_connection()
    if not conn:
        return jsonify([]), 200

    cursor = conn.cursor()
    try:
        if q:
            # Match any words typed (e.g., "sandaru fever" finds "fever")
            like_q = "%" + "%".join(q.split()) + "%"
            cursor.execute("""
                SELECT id, name 
                FROM complaint_tags 
                WHERE LOWER(name) LIKE %s 
                ORDER BY name 
                LIMIT 20
            """, (like_q,))
        else:
            cursor.execute("SELECT id, name FROM complaint_tags ORDER BY name LIMIT 50")

        rows = cursor.fetchall()
        results = [{'id': r[0], 'name': r[1]} for r in rows]
        return jsonify(results), 200
    except Exception as e:
        print("Error fetching complaint tags:", e)
        return jsonify([]), 200
    finally:
        cursor.close()
        conn.close()


@patient_history_bp.route('/present_complaints/all', methods=['GET'])
@jwt_required()
@role_required('doctor')
def get_all_complaints():
    conn = get_db_connection()
    if not conn:
        return jsonify([]), 200
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT id, name FROM complaint_tags ORDER BY name")
        rows = cursor.fetchall()
        results = [{'id': r[0], 'name': r[1]} for r in rows]
        return jsonify(results), 200
    except Exception as e:
        print("Error fetching all complaints:", e)
        return jsonify([]), 200
    finally:
        cursor.close()
        conn.close()


# -------------------- INVESTIGATION ROUTES --------------------

@patient_history_bp.route('/investigations', methods=['POST'])
@jwt_required()
@role_required('doctor')
def add_investigation():
    """Add a new investigation item"""
    data = request.get_json() or {}
    name = (data.get('name') or "").strip()
    if not name:
        return jsonify({'error': 'Missing name'}), 400

    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'DB connection failed'}), 500
    cursor = conn.cursor()
    try:
        cursor.execute("INSERT INTO investigations (name) VALUES (%s)", (name,))
        conn.commit()
        return jsonify({'message': 'saved', 'id': cursor.lastrowid, 'name': name}), 200
    except mysql.connector.IntegrityError:
        conn.rollback()
        cursor.execute("SELECT id FROM investigations WHERE name=%s", (name,))
        row = cursor.fetchone()
        return jsonify({'message': 'already_exists', 'id': row[0] if row else None, 'name': name}), 200
    except Exception as e:
        print("Error saving investigation:", e)
        conn.rollback()
        return jsonify({'error': str(e)}), 500
    finally:
        cursor.close()
        conn.close()


@patient_history_bp.route('/investigations', methods=['GET'])
@jwt_required()
@role_required('doctor')
def get_investigations():
    """Fetch all investigations"""
    conn = get_db_connection()
    if not conn:
        return jsonify([]), 200
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT id, name FROM investigations ORDER BY id ASC")
        rows = cursor.fetchall()
        results = [{'id': r[0], 'name': r[1]} for r in rows]
        return jsonify(results), 200
    except Exception as e:
        print("Error fetching investigations:", e)
        return jsonify([]), 200
    finally:
        cursor.close()
        conn.close()


@patient_history_bp.route('/investigations/<int:id>', methods=['DELETE'])
@jwt_required()
@role_required('doctor')
def delete_investigation(id):
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'DB connection failed'}), 500
    cursor = conn.cursor()
    try:
        cursor.execute("DELETE FROM investigations WHERE id=%s", (id,))
        conn.commit()
        return jsonify({'message': 'deleted'}), 200
    except Exception as e:
        conn.rollback()
        return jsonify({'error': str(e)}), 500
    finally:
        cursor.close()
        conn.close()


import json

@patient_history_bp.route('/save_patient_data', methods=['POST'])
@jwt_required()
@role_required('doctor')
def save_patient_data():
    data = request.json
    patient_id = data.get("patient_id")

    if not patient_id:
        return jsonify({"status": "error", "error": "Missing patient_id"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        sql = """
        INSERT INTO patient_investigations
        (patient_id, present_complaint, past_history, family_history,
         symptoms, probable_diagnosis, investigations, remarks, clinician, created_at)
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,NOW())
        """
        cursor.execute(sql, (
            patient_id,
            data.get('present_complaint', ''),
            data.get('past_history', ''),
            data.get('family_history', ''),
            data.get('symptoms', ''),
            data.get('probable_diagnosis', ''),
            json.dumps(data.get('investigations', [])),  # ✅ store as JSON string
            data.get('remarks', ''),
            data.get('clinician', '')
        ))

        conn.commit()
        investigation_id = cursor.lastrowid  # ✅ Get the newly inserted investigation ID

        cursor.close()
        conn.close()

        return jsonify({
            "status": "success",
            "message": "Patient data saved successfully!",
            "investigation_id": investigation_id  # ✅ send back to frontend
        })

    except Exception as e:
        print("Error saving patient data:", e)
        return jsonify({"status": "error", "error": str(e)}), 500
    
    
    
    
from datetime import datetime

@patient_history_bp.route('/get-investigation/<int:inv_id>', methods=['GET'])
@jwt_required()
@role_required('doctor')
def get_single_investigation(inv_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    try:
        cursor.execute("""
            SELECT id, patient_id, present_complaint, past_history, family_history,
                   symptoms, probable_diagnosis, investigations, remarks, created_at
            FROM patient_investigations
            WHERE id = %s
        """, (inv_id,))

        row = cursor.fetchone()
        if not row:
            return jsonify({"status": "error", "message": "Investigation not found"}), 404

        # Convert JSON string → List
        investigations_list = json.loads(row["investigations"]) if row["investigations"] else []

        # Format created_at
        created_at_formatted = None
        if row["created_at"]:
            if isinstance(row["created_at"], str):
                # If it comes as string, parse to datetime first
                dt_obj = datetime.strptime(row["created_at"], "%Y-%m-%d %H:%M:%S")
            else:
                dt_obj = row["created_at"]
            created_at_formatted = dt_obj.strftime("%Y/%m/%d %I:%M:%S %p")  # 12-hour format with AM/PM

        return jsonify({
            "status": "success",
            "investigation": {
                "id": row["id"],
                "patient_id": row["patient_id"],
                "created_at": created_at_formatted,
                "present_complaint": row["present_complaint"],
                "symptoms": row["symptoms"],
                "probable_diagnosis": row["probable_diagnosis"],
                "remarks": row["remarks"],
                "investigations": investigations_list
            }
        }), 200

    except Exception as e:
        print("Get investigation error:", e)
        return jsonify({"status": "error", "message": str(e)}), 500
    finally:
        cursor.close()
        conn.close()



@patient_history_bp.route('/update-investigation/<int:investigation_id>', methods=['POST'])
@jwt_required()
@role_required('doctor')
def update_investigation(investigation_id):
    data = request.json or {}
    new_items = data.get("investigations", [])

    if not isinstance(new_items, list):
        return jsonify({"status": "error", "message": "Invalid investigations format"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)

        # Get patient_id first
        cursor.execute("SELECT patient_id FROM patient_investigations WHERE id = %s", (investigation_id,))
        row = cursor.fetchone()
        if not row:
            return jsonify({"status": "error", "message": "Investigation not found"}), 404

        patient_id = row["patient_id"]

        # Update investigations
        sql = "UPDATE patient_investigations SET investigations = %s WHERE id = %s"
        cursor.execute(sql, (json.dumps(new_items), investigation_id))
        conn.commit()

        cursor.close()
        conn.close()

        return jsonify({
            "status": "success",
            "message": "Investigation updated successfully!",
            "patient_id": patient_id  # ✅ include patient ID
        })

    except Exception as e:
        print("Error updating investigation:", e)
        return jsonify({"status": "error", "message": str(e)}), 500


@patient_history_bp.route('/lab-results', methods=['POST'])
@jwt_required()
@role_required('doctor')
def add_lab_result():
    data = request.get_json() or {}

    patient_id = data.get('patient_id')
    investigation_id = data.get('investigation_id')
    lab_date = data.get('lab_date')
    results = data.get('results')  # List of dicts: [{investigation_id, value}]
    notes = data.get('notes', "")

    if not all([patient_id, investigation_id, lab_date, results]):
        return jsonify({'status': 'error', 'message': 'Missing required fields'}), 400

    conn = get_db_connection()
    if not conn:
        return jsonify({'status': 'error', 'message': 'DB connection failed'}), 500
    cursor = conn.cursor()
    try:
        cursor.execute("""
            INSERT INTO lab_results (patient_id, investigation_id, lab_date, results, notes)
            VALUES (%s, %s, %s, %s, %s)
        """, (patient_id, investigation_id, lab_date, json.dumps(results), notes))
        conn.commit()
        return jsonify({
            'status': 'success',
            'id': cursor.lastrowid,
            'patient_id': patient_id,
            'investigation_id': investigation_id
        }), 200
    except Exception as e:
        print("Error saving lab result:", e)
        conn.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500
    finally:
        cursor.close()
        conn.close()
