# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# Licensed under the MIT License

"""Social Worker case management routes — /api/cases/*."""

from __future__ import annotations

from flask import Blueprint, jsonify, request

from ..auth import require_auth
from ..helpers import get_agent, safe_error

bp = Blueprint("social_worker", __name__)


# Social Worker Cases CRUD API
# ============================================================


@bp.route("/api/cases")
@require_auth
def api_cases_list():
    """List all cases."""
    from familiar.dashboard.cases_crud import get_all_cases

    return jsonify({"cases": get_all_cases()})


@bp.route("/api/cases", methods=["POST"])
@require_auth
def api_cases_create():
    """Create a new case."""
    from familiar.dashboard.cases_crud import add_case

    data = request.get_json(force=True)
    case = add_case(data)
    return jsonify({"case": case}), 201


@bp.route("/api/cases/<case_id>", methods=["PUT"])
@require_auth
def api_cases_update(case_id):
    """Update a case."""
    from familiar.dashboard.cases_crud import update_case

    data = request.get_json(force=True)
    data["id"] = case_id
    result = update_case(data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"case": result})


@bp.route("/api/cases/<case_id>", methods=["DELETE"])
@require_auth
def api_cases_delete(case_id):
    """Delete a case."""
    from familiar.dashboard.cases_crud import delete_case

    result = delete_case(case_id)
    if "error" in result:
        return jsonify(result), 404
    return jsonify(result)


@bp.route("/api/cases/<case_id>/interaction", methods=["POST"])
@require_auth
def api_cases_interaction(case_id):
    """Add an interaction to a case."""
    from familiar.dashboard.cases_crud import add_case_interaction

    data = request.get_json(force=True)
    data["case_id"] = case_id
    result = add_case_interaction(data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"case": result})


@bp.route("/api/cases/resources")
@require_auth
def api_resources_list():
    """List all resources."""
    from familiar.dashboard.cases_crud import get_all_resources

    return jsonify({"resources": get_all_resources()})


@bp.route("/api/cases/resources", methods=["POST"])
@require_auth
def api_resources_create():
    """Create a new resource."""
    from familiar.dashboard.cases_crud import add_resource

    data = request.get_json(force=True)
    resource = add_resource(data)
    return jsonify({"resource": resource}), 201


@bp.route("/api/cases/resources/<res_id>", methods=["PUT"])
@require_auth
def api_resources_update(res_id):
    """Update a resource."""
    from familiar.dashboard.cases_crud import update_resource

    data = request.get_json(force=True)
    data["id"] = res_id
    result = update_resource(data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"resource": result})


@bp.route("/api/cases/resources/<res_id>", methods=["DELETE"])
@require_auth
def api_resources_delete(res_id):
    """Delete a resource."""
    from familiar.dashboard.cases_crud import delete_resource

    result = delete_resource(res_id)
    if "error" in result:
        return jsonify(result), 404
    return jsonify(result)


@bp.route("/api/cases/notes")
@require_auth
def api_case_notes_list():
    """List all case notes."""
    from familiar.dashboard.cases_crud import get_all_case_notes

    return jsonify({"notes": get_all_case_notes()})


@bp.route("/api/cases/notes", methods=["POST"])
@require_auth
def api_case_notes_create():
    """Add a case note."""
    from familiar.dashboard.cases_crud import add_case_note

    data = request.get_json(force=True)
    note = add_case_note(data)
    return jsonify({"note": note}), 201


@bp.route("/api/cases/notes/<note_id>", methods=["DELETE"])
@require_auth
def api_case_notes_delete(note_id):
    """Delete a case note."""
    from familiar.dashboard.cases_crud import delete_case_note

    result = delete_case_note(note_id)
    if "error" in result:
        return jsonify(result), 404
    return jsonify(result)


@bp.route("/api/cases/crisis")
@require_auth
def api_crisis_list():
    """List all crisis events."""
    from familiar.dashboard.cases_crud import get_all_crisis_events

    return jsonify({"crisis_log": get_all_crisis_events()})


@bp.route("/api/cases/crisis", methods=["POST"])
@require_auth
def api_crisis_create():
    """Log a crisis event."""
    from familiar.dashboard.cases_crud import add_crisis_event

    data = request.get_json(force=True)
    event = add_crisis_event(data)
    return jsonify({"event": event}), 201


@bp.route("/api/cases/crisis/<event_id>", methods=["DELETE"])
@require_auth
def api_crisis_delete(event_id):
    """Delete a crisis event."""
    from familiar.dashboard.cases_crud import delete_crisis_event

    result = delete_crisis_event(event_id)
    if "error" in result:
        return jsonify(result), 404
    return jsonify(result)


# ── Clinical Assessments & Safety Plans (HMIS / SAMHSA) ──


@bp.route("/api/cases/<case_id>/assessments")
@require_auth
def api_case_assessments_list(case_id):
    """List assessments for a case."""
    from familiar.dashboard.cases_crud import get_assessments

    return jsonify({"assessments": get_assessments(case_id)})


@bp.route("/api/cases/<case_id>/assessments", methods=["POST"])
@require_auth
def api_case_assessments_create(case_id):
    """Add a clinical assessment (PHQ-9, GAD-7, C-SSRS, AUDIT, DAST-10, ACE)."""
    from familiar.dashboard.cases_crud import add_assessment

    data = request.get_json(force=True)
    result = add_assessment(case_id, data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"assessment": result}), 201


@bp.route("/api/cases/<case_id>/safety-plan", methods=["GET"])
@require_auth
def api_case_safety_plan_get(case_id):
    """Get safety plan for a case."""
    from familiar.dashboard.cases_crud import get_all_cases

    for case in get_all_cases():
        if case["id"] == case_id:
            return jsonify({"safety_plan": case.get("safety_plan", {})})
    return jsonify({"error": f"Case {case_id} not found"}), 404


@bp.route("/api/cases/<case_id>/safety-plan", methods=["POST"])
@require_auth
def api_case_safety_plan_save(case_id):
    """Save or update a Stanley-Brown safety plan."""
    from familiar.dashboard.cases_crud import save_safety_plan

    data = request.get_json(force=True)
    result = save_safety_plan(case_id, data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"safety_plan": result})


@bp.route("/api/cases/<case_id>/mandatory-reports", methods=["POST"])
@require_auth
def api_case_mandatory_report(case_id):
    """Log a mandatory report."""
    from familiar.dashboard.cases_crud import add_mandatory_report

    data = request.get_json(force=True)
    result = add_mandatory_report(case_id, data)
    if "error" in result:
        return jsonify(result), 404
    return jsonify({"report": result}), 201

