Give me detailed comparison between type 1 diabetes mellitus vs type 2 diabetes mellitus.

I'll start by reading the medical library skill, then search for comprehensive information on both types of diabetes simultaneously.
Reading File

Give me detailed comparison between type 1 diabetes mellitus vs type 2 diabetes mellitus.

Reading File
Searching sources...
Now I'll run parallel searches across the medical library for comprehensive coverage.
Finding Sources
Finding Sources
Searching Images

type 1 vs type 2 diabetes mellitus comparison pathophysiology

A pathophysiology diagram illustrating the mechanisms of endothelial dysfunction and increased cardiovascular risk in Type 1 and Type 2 Diabetes Mellitus. The diagram shows a cross-section of a blood vessel lined with endothelial cells. The upper section depicts pathological outcomes including the formation and destabilization of atherosclerotic plaques, increased coagulation (platelet aggregation), dysregulation of arterial blood pressure, and increased inflammation. Centrally, a list summarizes the resulting vascular environment: decreased platelet inhibition and vasodilation, alongside increased vasoconstriction and endothelial permeability. The lower section outlines the biochemical triggers: hyperglycemia leading to advanced glycation end-product (AGE) formation and RAGE binding; elevated plasma free fatty acids (FFAs); and imbalances in matrix metalloproteinases. These factors, alongside insulin resistance and oxidative stress, drive the dysfunction by decreasing nitric oxide and prostacyclin production while increasing endothelin-1, tissue factor, and cell adhesion molecule (CAM) expression. The diagram serves as a conceptual map connecting metabolic derangements to clinical macrovascular and microvascular complications.

A pathophysiology diagram illustrating the mechanisms of endothelial dysfunction and increased cardiovascular risk in Type 1 and Type 2 Diabetes Mellitus. The diagram shows a cross-section of a blood vessel lined with endothelial cells. The upper section depicts pathological outcomes including the formation and destabilization of atherosclerotic plaques, increased coagulation (platelet aggregation), dysregulation of arterial blood pressure, and increased inflammation. Centrally, a list summarizes the resulting vascular environment: decreased platelet inhibition and vasodilation, alongside increased vasoconstriction and endothelial permeability. The lower section outlines the biochemical triggers: hyperglycemia leading to advanced glycation end-product (AGE) formation and RAGE binding; elevated plasma free fatty acids (FFAs); and imbalances in matrix metalloproteinases. These factors, alongside insulin resistance and oxidative stress, drive the dysfunction by decreasing nitric oxide and prostacyclin production while increasing endothelin-1, tissue factor, and cell adhesion molecule (CAM) expression. The diagram serves as a conceptual map connecting metabolic derangements to clinical macrovascular and microvascular complications.

A medical infographic and comparison chart illustrating the sex-specific pathophysiology of microvascular function in Type 2 Diabetes Mellitus (T2DM). The diagram compares middle-aged men and postmenopausal women. For men, the visual highlights that despite higher glycemia (indicated by double upward arrows), they exhibit 'normal microvascular function,' depicted by a blood vessel with a smooth endothelium and organized red blood cells. In contrast, postmenopausal women are shown with lower glycemia (single upward arrow) yet manifest 'impaired microvascular function,' visually represented by an irregular, damaged vessel lining with projections. This vascular impairment in women is further linked to a specific metabolic profile: decreased levels of the anti-inflammatory adipokine adiponectin and increased levels of pro-inflammatory mediators, specifically C-reactive protein (CRP) and advanced glycation end products (AGEs). The illustration serves as a clinical comparison of how hormonal status and inflammatory markers, rather than glycemia alone, drive microvascular complications in diabetic women.

A medical infographic and comparison chart illustrating the sex-specific pathophysiology of microvascular function in Type 2 Diabetes Mellitus (T2DM). The diagram compares middle-aged men and postmenopausal women. For men, the visual highlights that despite higher glycemia (indicated by double upward arrows), they exhibit 'normal microvascular function,' depicted by a blood vessel with a smooth endothelium and organized red blood cells. In contrast, postmenopausal women are shown with lower glycemia (single upward arrow) yet manifest 'impaired microvascular function,' visually represented by an irregular, damaged vessel lining with projections. This vascular impairment in women is further linked to a specific metabolic profile: decreased levels of the anti-inflammatory adipokine adiponectin and increased levels of pro-inflammatory mediators, specifically C-reactive protein (CRP) and advanced glycation end products (AGEs). The illustration serves as a clinical comparison of how hormonal status and inflammatory markers, rather than glycemia alone, drive microvascular complications in diabetic women.

This Comparison Chart illustrates brain network connectivity alterations in patients with Type 2 Diabetes Mellitus (T2DM) and Mild Cognitive Impairment (MCI) using three axial-view brain mapping diagrams. The visualization identifies specific anatomical regions as red nodes and functional or structural connections as blue edges. Panel 1 (T2DM with MCI vs HCs) displays a dense network of eight nodes, including the Left and Right Superior Frontal Gyrus (SOFG), Left Inferior Frontal Gyrus (IOFG), Left Anterior Cingulate Gyrus (ACG), Bilateral Hippocampus (HIP), Left Inferior Temporal Gyrus (ITG), and Right Superior Occipital Gyrus (SOG), indicating significant connectivity differences compared to healthy controls. Panel 2 (T2DM with MCI vs T2DM without MCI) reveals a simpler four-node network with a prominent edge connecting the SOFG.L and ACG.L, highlighting regional alterations associated specifically with cognitive decline in diabetic patients. Panel 3 (T2DM without MCI vs HCs) shows an empty brain template, indicating no significant network differences between these groups. This visualization demonstrates the neuro-pathophysiological progression of T2DM-related cognitive impairment through graph theory analysis.

This Comparison Chart illustrates brain network connectivity alterations in patients with Type 2 Diabetes Mellitus (T2DM) and Mild Cognitive Impairment (MCI) using three axial-view brain mapping diagrams. The visualization identifies specific anatomical regions as red nodes and functional or structural connections as blue edges. Panel 1 (T2DM with MCI vs HCs) displays a dense network of eight nodes, including the Left and Right Superior Frontal Gyrus (SOFG), Left Inferior Frontal Gyrus (IOFG), Left Anterior Cingulate Gyrus (ACG), Bilateral Hippocampus (HIP), Left Inferior Temporal Gyrus (ITG), and Right Superior Occipital Gyrus (SOG), indicating significant connectivity differences compared to healthy controls. Panel 2 (T2DM with MCI vs T2DM without MCI) reveals a simpler four-node network with a prominent edge connecting the SOFG.L and ACG.L, highlighting regional alterations associated specifically with cognitive decline in diabetic patients. Panel 3 (T2DM without MCI vs HCs) shows an empty brain template, indicating no significant network differences between these groups. This visualization demonstrates the neuro-pathophysiological progression of T2DM-related cognitive impairment through graph theory analysis.

A pathophysiology diagram illustrating the molecular mechanisms linking Type 2 Diabetes Mellitus (T2DM) to cognitive dysfunction. The pathway begins with a High-Fat Diet (HFD) and Streptozotocin (STZ) induction in a rat model, leading to increased serum Interleukin-6 (IL-6) and subsequent hippocampal TNF-α expression. This inflammatory state disrupts normal insulin signaling at the Insulin Receptor Substrate (IRS) level. Under normal conditions, IRS stimulates the PI3K/AKT pathway. However, the diagram shows an 'abnormal pathway' where increased TNF-α leads to decreased PI3K and AKT activity. This downregulation fails to inhibit Glycogen Synthase Kinase 3 beta (GSK-3β). Simultaneously, there is an upregulation of Tau Tubulin Kinase 1 (TTBK 1). The synergistic effect of increased GSK-3β and TTBK 1 activity drives the hallmark pathological features of Alzheimer-like neurodegeneration: increased amyloid aggregation and increased tau phosphorylation. The diagram uses solid arrows for stimulation, T-bars for inhibition, and dashed arrows to represent abnormal disease-state pathways.

A pathophysiology diagram illustrating the molecular mechanisms linking Type 2 Diabetes Mellitus (T2DM) to cognitive dysfunction. The pathway begins with a High-Fat Diet (HFD) and Streptozotocin (STZ) induction in a rat model, leading to increased serum Interleukin-6 (IL-6) and subsequent hippocampal TNF-α expression. This inflammatory state disrupts normal insulin signaling at the Insulin Receptor Substrate (IRS) level. Under normal conditions, IRS stimulates the PI3K/AKT pathway. However, the diagram shows an 'abnormal pathway' where increased TNF-α leads to decreased PI3K and AKT activity. This downregulation fails to inhibit Glycogen Synthase Kinase 3 beta (GSK-3β). Simultaneously, there is an upregulation of Tau Tubulin Kinase 1 (TTBK 1). The synergistic effect of increased GSK-3β and TTBK 1 activity drives the hallmark pathological features of Alzheimer-like neurodegeneration: increased amyloid aggregation and increased tau phosphorylation. The diagram uses solid arrows for stimulation, T-bars for inhibition, and dashed arrows to represent abnormal disease-state pathways.

Now I'll read the most authoritative sources in parallel - Harrison's for both T1DM and T2DM, plus the Family Medicine textbook and Katzung's pharmacology sections.
Reading File
Reading File
Finding Sources
Now let me read Harrison's dedicated T1DM and T2DM sections, and also get the Swanson's and Katzung sections in parallel.
Reading File
Reading File
Finding Sources
Excellent data. Now let me read the deeper Harrison's T2DM section and the Lippincott pharmacology, Miller's anesthesia, and Swanson's T2DM sections in parallel.
Reading File
Reading File
Reading File
Reading File
I found a key insulin release graph image. Let me fetch it and also get the Harrison's early diabetes section for the foundational overview, plus the Henry's Clinical Lab section.
Loading Image
Reading File
Finding Sources
I now have very rich data from multiple authoritative sources. Let me compile the comprehensive comparison.

Type 1 Diabetes Mellitus vs Type 2 Diabetes Mellitus - Detailed Comparison


1. Overview / Definition

FeatureType 1 DM (T1DM)Type 2 DM (T2DM)
Core defectAbsolute insulin deficiency due to destruction of pancreatic beta cellsInsulin resistance with relative (not absolute) insulin deficiency
Proportion of all DM~5-10% of cases~90-95% of all cases
Former namesJuvenile-onset DM, Insulin-dependent DM (IDDM)Adult-onset DM, Non-insulin-dependent DM (NIDDM)

2. Etiology & Pathogenesis

Type 1 DM

  • Autoimmune destruction of beta cells in the pancreatic islets of Langerhans, resulting in complete loss of insulin production.
  • Environmental triggers (viral infections, toxins, possibly vitamin D deficiency) may initiate the autoimmune cascade in genetically predisposed individuals.
  • A prediabetes period of gradual beta cell destruction can last months to decades. During this silent phase, the first-phase insulin release to IV glucose becomes depressed or absent.
  • Eventually, most or all beta cells are destroyed, causing undetectable C-peptide and insulin levels. - Henry's Clinical Diagnosis and Management by Laboratory Methods
Autoantibodies found in T1DM:
  • Anti-GAD65 (glutamic acid decarboxylase) - highest sensitivity (91%) as a single screening marker
  • Insulin autoantibodies (IAA) - more common in young children
  • IA-2 (insulinoma-associated protein 2, tyrosine phosphatase)
  • ZnT8A (zinc transporter 8) - located on secretory granule surface membranes
Individuals with ≥2 autoantibodies are at significantly increased risk of developing T1DM. - Henry's Clinical Diagnosis

Type 2 DM

  • Caused by insulin resistance combined with progressive beta cell dysfunction. Genetic susceptibility (≥18 polymorphisms identified by GWAS) interacts with environmental triggers.
  • Genetically susceptible individuals develop obesity, which induces physiologic stress and overproduction of insulin. Over time, programmed beta cell apoptosis begins.
  • By the time prediabetes is diagnosed (2-hour postprandial glucose 140-180 mg/dL), patients have already lost ~80% of beta cell function and are maximally insulin resistant. - Textbook of Family Medicine
  • Disease is progressive - ultimately requires multiple agents and often insulin.
  • Environmental triggers include obesity, high-fat diet, physical inactivity, vitamin D deficiency, concurrent illness, and certain medications (glucocorticoids, HIV medications). - Textbook of Family Medicine

3. Insulin Release Pattern

The graph below from Lippincott's Pharmacology perfectly illustrates the key difference:
Plasma insulin concentration in response to IV glucose infusion - Normal subjects show a sharp early peak, Type 2 shows a blunted delayed response, Type 1 shows a flat line (no response)
Figure: Release of insulin in response to an IV glucose load. Normal subjects show a sharp first-phase peak; Type 2 shows a blunted, delayed response; Type 1 shows a near-flat line. (Lippincott Illustrated Reviews: Pharmacology)
  • T1DM: No first-phase or second-phase insulin release - pancreas cannot respond to glucose at all.
  • T2DM: Loss of the early first-phase peak; slow, blunted second-phase response - insulin is still produced but insufficiently and with poor timing.

4. Epidemiology & Risk Factors

FeatureT1DMT2DM
Age at onsetTypically childhood, adolescence, young adults (can occur at any age; LADA appears in adults)Typically >45 years, increasingly younger
Body habitusUsually normal weight or thinUsually overweight or obese
SexRoughly equalSlightly more common in women with certain risk factors (PCOS, gestational DM history)
EthnicityAny; slight North European predominanceHigher in African Americans, Native Americans, Hispanics, Asians, Pacific Islanders
Family historyWeaker (3-5% risk if parent affected)Stronger (1st degree relative is major risk factor)
Metabolic syndromeNot typically associatedStrongly associated (HTN, dyslipidemia, abdominal obesity)
Other autoimmune diseasesFrequently associated (thyroid, celiac, Addison's)Not typically associated

5. Genetic Basis

T1DMT2DM
Key genesHLA-DR3, HLA-DR4 (chromosome 6); also non-HLA genes≥18 polymorphisms identified; no single HLA association
HLA associationStrong (HLA-DR/DQ on chromosome 6)Weak / absent
ModePolygenic + environmental triggerPolygenic + strong environmental influence (obesity, diet)
  • T2DM polymorphisms favor reduced satiety, increased appetite, reduced energy expenditure, and increased intraabdominal fat - Textbook of Family Medicine

6. Clinical Presentation

FeatureT1DMT2DM
OnsetAcute / abruptInsidious (often asymptomatic at diagnosis)
Classic symptoms (3 Ps)Polyuria, polydipsia, polyphagia - often dramatic and rapidOften absent or subtle - many found on screening
WeightWeight lossOften overweight or obese
Ketonemia/DKACommon - prone to DKA when insulin withheldRare - not prone to DKA; prone to HHS instead
At diagnosisOften symptomatic, may present in DKAOften asymptomatic; complications (e.g., retinopathy) may already be present

7. Laboratory / Diagnostic Features

Shared diagnostic criteria (same for both types) - Swanson's Family Medicine Review / Miller's Anesthesia:
  • Fasting plasma glucose ≥126 mg/dL (8-hour fast, confirmed on repeat)
  • Random glucose ≥200 mg/dL + symptoms of hyperglycemia
  • 2-hour plasma glucose ≥200 mg/dL during 75g OGTT
  • HbA1c ≥6.5%
Distinguishing laboratory features:
Lab FindingT1DMT2DM
C-peptideVery low or undetectableNormal or elevated (especially early); low in late-stage
Insulin levelsVery low / absentNormal, elevated (early); reduced (late)
Autoantibodies (GAD65, IA-2, IAA, ZnT8A)Positive (usually ≥2)Negative
HbA1c monitoringTarget <7% (gold standard)Same target
Prediabetes rangeFPG 100-125 mg/dL; OGTT 140-199 mg/dL; HbA1c 5.7-6.4%Same criteria

8. Acute Complications

ComplicationT1DMT2DM
Diabetic Ketoacidosis (DKA)Common, hallmark - due to absolute insulin deficiency causing unrestrained lipolysis and ketogenesisRare (may occur in severe illness)
Hyperosmolar Hyperglycemic State (HHS)RareMore common - due to relative insulin sufficiency preventing ketosis but not hyperglycemia
HypoglycemiaMore frequent (tight insulin control)Less frequent overall; occurs with insulin or sulfonylurea use
Hypoglycemic unawarenessCan develop with repeated episodesCan develop similarly
  • Miller's Anesthesia: "T1DM patients prone to ketoacidosis when insulin is withheld; T2DM patients prone to HHS during acute illness."

9. Chronic Complications (Shared, but timing differs)

Both types share the same spectrum of complications, but in T2DM, complications may already be present before diagnosis due to the insidious onset:
Microvascular (from chronic hyperglycemia):
  • Diabetic retinopathy - leading cause of blindness
  • Diabetic nephropathy - T2DM is the most common cause of chronic renal failure in the US (because T2DM is 10x more frequent)
  • Diabetic neuropathy (peripheral + autonomic)
Macrovascular (atherosclerotic):
  • Coronary heart disease
  • Peripheral vascular disease
  • Stroke / cerebrovascular disease
  • Endothelial dysfunction from hyperglycemia, AGE formation, elevated free fatty acids, oxidative stress, and insulin resistance drives both micro- and macrovascular disease. - Henry's Clinical Diagnosis
In T2DM, 18% of patients with prediabetes already have diabetic retinopathy before progressing to frank T2DM. - Textbook of Family Medicine

10. Treatment

Type 1 DM

Insulin is mandatory - there is no alternative. The goal is to mimic physiologic insulin secretion with:
Delivery MethodDescription
Multiple Daily Injections (MDI)Basal + prandial (bolus) dosing regimen
Continuous Subcutaneous Insulin Infusion (CSII) / Insulin pumpManual bolus entries
Sensor-Augmented PumpCGM + pump; suspends insulin when glucose is low
Automated Insulin Delivery (AID)CGM + pump + algorithm; adjusts basal rate in real-time
Insulin types used:
  • Rapid-acting (Aspart, Lispro, Glulisine): onset <15 min, peak 0.5-1.5h, duration 3-5h
  • Short-acting (Regular): onset 0.5-1h, peak 2-3h, duration 4-8h
  • Intermediate (NPH): onset 2-4h, peak 4-10h, duration 10-16h
  • Long-acting (Glargine, Detemir, Degludec): onset 1-9h, flat/no peak, duration 20-24h+
  • Harrison's Principles of Internal Medicine 22E

Type 2 DM

Stepwise, progressive pharmacologic approach centered on lifestyle first, then oral agents, then injectable therapy:
Drug ClassExampleMechanism
Biguanides (1st-line)MetforminReduces hepatic gluconeogenesis, modest increase in peripheral uptake; promotes weight loss
SulfonylureasGlipizide, GlimepirideStimulate beta cell insulin secretion (ATP-K+ channel)
MeglitinidesRepaglinideShort-acting insulin secretagogues
ThiazolidinedionesPioglitazoneInsulin sensitizers (PPARγ agonists)
Alpha-glucosidase inhibitorsAcarboseDelay carbohydrate absorption
DPP-4 inhibitorsSitagliptinIncrease incretin levels → glucose-dependent insulin secretion
GLP-1 receptor agonistsSemaglutide, LiraglutideStimulate glucose-dependent insulin secretion, suppress glucagon, promote weight loss, CV benefit
SGLT-2 inhibitorsEmpagliflozin, DapagliflozinPromote urinary glucose excretion; CV and renal protective benefits
InsulinAll typesWhen oral agents insufficient or in severe hyperglycemia
  • Metformin remains first-line; SGLT-2 inhibitors and GLP-1 agonists are preferred add-ons when CV/renal protection is needed - Harrison's 22E
  • 15-20% of T2DM patients ultimately require insulin - Swanson's Family Medicine Review

11. Monitoring Targets (Both Types)

ParameterTarget
HbA1c<7.0% (gold standard; checked every 3 months)
Fasting plasma glucose80-130 mg/dL
Post-meal glucose (2h)<180 mg/dL
Blood pressure<130/80 mmHg
LDL cholesterol<70 mg/dL (high CV risk)

12. Summary Comparison Table

FeatureType 1 DMType 2 DM
MechanismAutoimmune beta cell destructionInsulin resistance + progressive beta cell failure
InsulinAbsolute deficiencyRelative deficiency
Proportion5-10%90-95%
OnsetAcute, abruptInsidious, often asymptomatic
AgeUsually <30 years (any age)Usually >45 years (decreasing)
Body weightNormal/thinObese
AutoantibodiesPresent (GAD65, IA-2, ZnT8A, IAA)Absent
C-peptideVery low/absentNormal to high (early)
HLA associationStrong (DR3/DR4)Weak/absent
Ketosis/DKAProneRare
HHSRareProne
Hypoglycemia riskHigherLower (unless on insulin/SU)
Metabolic syndromeNot associatedStrongly associated
Other autoimmuneFrequently co-existsNot typically
TreatmentInsulin always requiredLifestyle → Metformin → add-on agents → insulin
ProgressionStable (beta cells already destroyed)Progressive over years/decades
ComplicationsSame spectrum; earlier if poor controlSame spectrum; may predate diagnosis

Sources

  • Harrison's Principles of Internal Medicine, 22E (2025)
  • Lippincott Illustrated Reviews: Pharmacology
  • Henry's Clinical Diagnosis and Management by Laboratory Methods
  • Miller's Anesthesia, 10E
  • Textbook of Family Medicine, 9E
  • Swanson's Family Medicine Review

Give me detailed treatment protocol for Type 2 Diabetes mellitus for both outpatient as well as inpatient. Give me step by step algorithm along with the preferred medications in view of associated comorbiditis. Also give me In every situation if blood sugar in elevated despite of given medicine what next step or next medicine to either add on or replace with. Make it interesting as well give me different scenarios of cases to make it more explainable.

Finding Sources
Finding Sources
Finding Sources
Finding Sources
Searching PubMed

"type 2 diabetes"[MeSH Terms] AND "practice guideline"[pt]

Reading File
Reading File
Finding Sources
Finding Sources
Reading Article

PMID: 39093266

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Searching the Web

ADA 2025 Standards of Care type 2 diabetes pharmacologic treatment algorithm metformin GLP-1 SGLT2

Searching the Web

inpatient glycemic management guidelines 2024 2025 basal bolus insulin target glucose critically ill

Type 2 Diabetes Mellitus - Complete Treatment Protocol (Outpatient + Inpatient)

Think of T2DM management as a branching decision tree, not a fixed recipe. The starting point is always lifestyle + metformin, but the road forks hard the moment a comorbidity (heart, kidney, weight, or age) enters the picture. I've built this as a working algorithm plus real-world case scenarios so you can see exactly how the branches play out.

PART A: OUTPATIENT ALGORITHM

Step 0 - Foundation (Every Patient, Every Time)

  • Lifestyle: medical nutrition therapy, weight management, exercise
  • Diabetes self-management education
  • Assess comorbidity profile first - this now determines drug choice independent of HbA1c, per the ADA/EASD consensus algorithm - Katzung's Pharmacology, Fig. 41-6, updated per ADA Standards of Care 2025

Step 1 - Ask "Does this patient have a compelling comorbidity?"

                    NEWLY DIAGNOSED T2DM
                            |
              Start Metformin + Lifestyle
                            |
        ┌───────────────────┼───────────────────┬─────────────────┐
        │                   │                   │                 │
   ASCVD / high        Heart Failure         CKD (esp.        Obesity /
   ASCVD risk           (esp. HFrEF)      albuminuria)      weight is priority
        │                   │                   │                 │
   SGLT2i and/or       SGLT2i preferred    SGLT2i (if eGFR    GLP-1 RA or
   GLP-1 RA with       (regardless of        ≥20) + max      dual GIP/GLP-1 RA
   proven CV benefit    A1c/metformin)      tolerated          (tirzepatide) -
   - regardless of                          metformin;         highest weight
   A1c                                      + finerenone       loss efficacy
                                             if albuminuria
                                             persists + K+ normal
  • Source: ADA Standards of Care 2025 Pharmacologic Treatment guideline; Goldman-Cecil Medicine; Comprehensive Clinical Nephrology 7E

Step 2 - No compelling comorbidity? Standard escalation ladder

LineDrugWhy
1stMetforminCheap, weight-neutral/loss, no hypoglycemia, cardio-safe
2nd (if A1c not at goal in ~3 months)Add SGLT2i or GLP-1 RA (preferred) OR pioglitazone/DPP-4i/SU depending on cost/access2025 ADA update favors early combination therapy rather than sequential monotherapy
3rdAdd a second agent from a different classCombine mechanisms - e.g., SGLT2i + GLP-1RA
4thInsulinWhen combination oral/injectable non-insulin therapy fails

PART B: "IF SUGAR STILL HIGH DESPITE DRUG X" - Escalation Logic

This is the part most people fumble. Here is the decision cascade at every failure point:
Current RegimenSugar still high - Next Step
Lifestyle aloneAdd metformin (unless eGFR <30 or contraindication)
Metformin alone, A1c above goalAdd SGLT2i or GLP-1 RA (comorbidity-driven) or 2nd agent
Metformin + 1 agent, still uncontrolledAdd a 3rd class with complementary mechanism (don't stack two secretagogues, e.g., don't add SU on top of meglitinide)
Triple oral/injectable therapy failingStart basal insulin at bedtime - keep metformin, SGLT2i, GLP-1RA running (only taper SU/DPP-4i due to redundancy and hypo risk)
Basal insulin + oral agents, fasting glucose controlled but daytime spikesAdd premixed insulin before breakfast/dinner, OR add prandial rapid-acting insulin at the largest meal ("basal-plus")
Basal-plus insulin still failingConvert to full basal-bolus (long-acting once/twice daily + rapid-acting before each meal)
Basal-bolus insulin + still poor control, weight gain, high doses (>1-1.5 U/kg/day)Suspect severe insulin resistance - add pioglitazone (watch edema/HF) or maximize GLP-1RA/SGLT2i; reassess adherence, injection technique, steroid use, infection
Any regimen + recurrent hypoglycemiaDe-intensify - drop sulfonylurea/meglitinide first, relax A1c target if elderly/frail, consider CGM
  • Sources: Katzung's Pharmacology Fig. 41-6; ADA Standards of Care 2025

PART C: COMORBIDITY-DRIVEN DRUG SELECTION (Cheat Sheet)

ComorbidityPreferredAvoid / Caution
ASCVD / high CV riskGLP-1 RA or SGLT2i with proven CV benefit-
Heart Failure (esp. HFrEF)SGLT2i is first-line regardless of A1c - reduces HF hospitalizationPioglitazone (fluid retention, contraindicated in HF); saxagliptin (some DPP-4i linked to HF hospitalization)
CKD/albuminuriaMetformin (down to eGFR 30, reduced dose 30-45) + SGLT2i (can continue to eGFR ~20) ± finerenone (nonsteroidal MRA) if albuminuria persists and K+ normalSGLT2i glucose-lowering effect weakens below eGFR 45 (but renal/CV protection persists); avoid metformin if eGFR <30
Obesity as priorityGLP-1 RA or dual GIP/GLP-1 RA (tirzepatide) - largest weight lossSulfonylureas, TZDs, insulin (all cause weight gain)
Elderly / frailDPP-4i (low hypoglycemia risk), cautious SGLT2i (volume depletion risk), simplified insulin regimensSulfonylureas (esp. glyburide) - hypoglycemia risk higher in elderly, renal/hepatic impairment - Katzung's Pharmacology
Hepatic impairmentInsulin is safest; metformin avoided in significant hepatic disease (lactic acidosis risk)Sulfonylureas (unpredictable clearance), pioglitazone (monitor LFTs)
History of pancreatitisAvoidGLP-1 RA, DPP-4i (theoretical pancreatitis association)

PART D: INPATIENT PROTOCOL

Golden Rule: Insulin is the cornerstone in the hospital. Oral agents are unreliable (slow onset, GI absorption issues, contraindications with contrast/fasting/renal changes) - Goodman & Gilman's Pharmacological Basis of Therapeutics

D1. Non-Critically Ill, Ward Patient (Eating)

Regimen: Basal-Bolus + Correction insulin (NOT sliding scale alone - RCT evidence shows sliding-scale-only is inferior)
ComponentDosing principle
Basal insulinLong-acting, once daily (~40-50% of total daily dose)
Prandial (bolus) insulinRapid-acting before each meal, adjusted to carb intake
Correction insulinAdded on top of bolus dose for unexpected hyperglycemia
Target140-180 mg/dL for most hospitalized patients
DPP-4 inhibitor + correction insulinNewer acceptable alternative for mild hyperglycemia in select non-T1DM patients (2025 update)
Home insulin pump / hybrid closed-loopCan be continued if patient/team capable of managing it

D2. Critically Ill / ICU Patient

Regimen: IV insulin infusion (variable rate) - preferred because of short half-life and titratability with rapidly changing hemodynamics, nutrition, and pressor use.
ParameterValue
Target glucose140-180 mg/dL (ADA 2025, SCCM 2024, ACP)
Start/intensify insulin infusionPersistent glucose >180 mg/dL
Avoid tight controlTargets <140 mg/dL increase hypoglycemia risk without added benefit (per RCT evidence)
Permissive higher target (up to 250)Consider in advanced renal failure or labile/high hypoglycemia-risk patients

D3. Perioperative Patient

StepAction
Preop HbA1c checkIf >8%, consider delaying elective surgery (independently associated with wound infection and mortality)
Insulin dose while fastingReduce stable home dose by 1/3 to 1/2
SGLT2 inhibitorsSTOP 3-4 days before surgery (FDA 2020 warning) - risk of euglycemic DKA postoperatively
Insulin pump patientsCan continue in OR if team is comfortable programming it; maintain basal rate unless glucose <110 (then reduce) or >180 (correction dose); check glucose at least hourly
ERAS protocolsCarbohydrate drinks up to 2h preop reduce catabolism/hypoglycemia risk in diabetics
Source: Current Surgical Therapy, 14E

D4. Hyperglycemic Emergencies (DKA / HHS)

DKAHHS
Typical patientCan occur in T2DM under severe stress (infection, MI, missed insulin)Classic T2DM presentation
Core therapyIV fluids (isotonic saline) → insulin infusion (fixed rate, e.g. 0.1 U/kg/h) → potassium replacement before/with insulin (insulin drives K+ intracellularly) → address underlying triggerAggressive fluid resuscitation is the priority; low-dose insulin (~0.05 U/kg/h) only if significant ketonemia present; correct slowly to avoid cerebral edema
LocationICU or intermediate care for continuous monitoringSame - large fluid/electrolyte shifts require monitored bed
Source: Bradley and Daroff's Neurology in Clinical Practice; Goldman-Cecil Medicine; Washington Manual of Medical Therapeutics

PART E: CASE SCENARIOS (Putting It All Together)

🩺 Case 1 - "The Textbook Start"

Rohan, 48, newly diagnosed T2DM, A1c 7.8%, obese, no other disease. → Lifestyle + Metformin first-line. → 3 months later A1c still 7.6% → add GLP-1 RA (also helps his weight) rather than a sulfonylurea. → Lesson: No compelling comorbidity = standard ladder, but 2025 ADA favors early combo therapy over waiting for monotherapy to "fail."

🫀 Case 2 - "The Post-MI Patient"

Meena, 62, T2DM, A1c 7.2% (already near goal), had an MI 6 months ago. → Even though her A1c is near goal, guidelines say add SGLT2i or GLP-1 RA with proven CV benefit regardless of A1c. → Lesson: Comorbidity, not glucose number, drives the choice here.

💧 Case 3 - "The Failing Kidneys"

Abdul, 70, T2DM x15 years, eGFR 38, albuminuria +. → Continue metformin at reduced dose (safe until eGFR 30). → Add SGLT2i (renal-protective, still effective glucose-wise until eGFR ~45, protective benefit persists below that). → Albuminuria persists despite max ACEi/ARB + SGLT2i, K+ normal → add finerenone. → Lesson: CKD changes both the ceiling (metformin dose) and the priority drug (SGLT2i + MRA add-on).

❤️ Case 4 - "Swollen Ankles and Short of Breath"

Grace, 68, T2DM, HFrEF (EF 35%).SGLT2i first-line, independent of A1c or metformin use - reduces HF hospitalizations. → Avoid pioglitazone (fluid retention - could worsen HF) and be cautious with certain DPP-4i (saxagliptin linked to HF hospitalization signal).

⚖️ Case 5 - "Weight is the Whole Battle"

Farah, 39, BMI 38, T2DM A1c 8.0%, no vascular disease yet.Dual GIP/GLP-1 RA (tirzepatide) or GLP-1 RA - best glucose AND weight outcomes. → Avoid sulfonylureas/insulin/TZDs as first add-on (weight gain).

👵 Case 6 - "The Frail Grandmother"

Lakshmi, 82, mild cognitive impairment, eGFR 45, on glyburide from years ago, having recurrent hypoglycemic episodes.Stop glyburide (long-acting SU + elderly + renal impairment = highest hypoglycemia risk category). → Switch to DPP-4 inhibitor (low hypo risk) or cautious low-dose basal insulin with relaxed A1c target (~8%). → Lesson: In the elderly, safety (avoiding hypoglycemia) often outweighs tight glycemic control.

🏥 Case 7 - "Sugar 280 on the Medical Ward"

Mr. Verma, 55, admitted for pneumonia, known T2DM on metformin + sulfonylurea at home, glucose now running 250-300, eating normally. → Hold oral agents (unreliable in acute illness). → Start basal-bolus insulin + correction scale, target 140-180 mg/dL. → Lesson: Even oral-agent-controlled outpatients often need insulin during acute hospitalization - no sliding-scale-only regimens.

🚨 Case 8 - "Crashing in the ICU"

Same patient develops septic shock, moved to ICU, glucose now unpredictable 180-320 on pressors. → Switch to IV insulin infusion, titrate to keep glucose 140-180 mg/dL; avoid over-tight control (<140) which raises hypoglycemia risk without proven benefit.

🔪 Case 9 - "Elective Surgery Coming Up"

Mrs. Iyer, 60, T2DM on metformin + empagliflozin (SGLT2i), A1c 9.5%, scheduled for elective hip replacement in 3 weeks. → HbA1c >8% → discuss delaying surgery if feasible to optimize control. → Stop the SGLT2i 3-4 days before surgery to avoid euglycemic DKA. → Reduce basal insulin/oral regimen dose while fasting; consider ERAS carbohydrate drink protocol.

🆘 Case 10 - "Found Down, Fruity Breath"

26-year-old (or a T2DM patient under severe septic stress) presents obtunded, glucose 480, ketones positive, pH 7.05. → This is DKA: aggressive isotonic fluids → IV insulin infusionreplace potassium concurrently (insulin will drop serum K+ further) → identify and treat trigger (infection, MI, non-adherence) → ICU-level monitoring.

🌊 Case 11 - "The Confused Elderly Man, No Ketones"

78-year-old nursing home resident, glucose 850, mildly confused, no ketones, osmolality markedly elevated. → This is HHS: fluids are the primary therapy; low-dose insulin only if significant ketonemia present; correct slowly to prevent cerebral edema/overly rapid osmotic shifts.

Quick-Reference Master Algorithm (Memorize This Shape)

LIFESTYLE + METFORMIN (always, unless contraindicated)
        │
        ▼
Compelling comorbidity? ──YES──► SGLT2i/GLP-1RA (ASCVD, HF, CKD)
        │                         or GLP-1RA/tirzepatide (obesity)
        NO
        ▼
Standard 2nd agent (SGLT2i/GLP-1RA preferred > DPP-4i/SU/TZD)
        │
   Still uncontrolled?
        ▼
3rd agent, different mechanism
        │
   Still uncontrolled?
        ▼
BASAL INSULIN at bedtime (keep metformin/SGLT2i/GLP-1RA; drop SU/DPP-4i)
        │
   Fasting good, daytime spikes?
        ▼
BASAL-PLUS (add prandial insulin at biggest meal) or premixed insulin
        │
   Still uncontrolled?
        ▼
FULL BASAL-BOLUS regimen
        │
   Recurrent hypoglycemia at any stage → step BACK, de-intensify, relax target
Note: Recent evidence flags a shift worth watching - the 2025-2026 ADA Standards of Care increasingly favor early combination therapy (metformin + SGLT2i/GLP-1RA together at diagnosis in high-risk patients) rather than the older "fail metformin first" sequential approach. If you're using an older textbook algorithm as reference, apply this update on top of it.

Create a clinical decision-making flowchart PDF I can print and use in clinic

Reading File
Reading File
Running Command

mkdir -p /tmp/workspace/t2dm-flowchart/output && ls -la /tmp/workspace/

Writing File

~/t2dm-flowchart/generate_flowchart.py

import math
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import landscape, LETTER
from reportlab.lib import colors
from reportlab.pdfbase.pdfmetrics import stringWidth

PAGE_W, PAGE_H = landscape(LETTER)  # 792 x 612
OUT = "/tmp/workspace/t2dm-flowchart/output/T2DM_Clinical_Algorithm.pdf"

NAVY = colors.HexColor("#0B3D91")
BLUE = colors.HexColor("#1D6FB8")
LIGHT_BLUE = colors.HexColor("#EAF2FB")
GREEN = colors.HexColor("#1E7B45")
LIGHT_GREEN = colors.HexColor("#EAF7EE")
PURPLE = colors.HexColor("#6A3D9A")
LIGHT_PURPLE = colors.HexColor("#F1E9F8")
TEAL = colors.HexColor("#0E7C7B")
LIGHT_TEAL = colors.HexColor("#E6F5F5")
ORANGE = colors.HexColor("#C1610B")
LIGHT_ORANGE = colors.HexColor("#FDF0E3")
RED = colors.HexColor("#B12A2A")
LIGHT_RED = colors.HexColor("#FBEAEA")
GREY = colors.HexColor("#555555")
LIGHT_GREY = colors.HexColor("#F2F6FC")
YELLOW_BG = colors.HexColor("#FFF3CD")

# ---------- helpers ----------

def wrap_text(text, font_name, font_size, max_width):
    words = text.split()
    lines = []
    cur = ""
    for w in words:
        test = (cur + " " + w).strip()
        if stringWidth(test, font_name, font_size) <= max_width:
            cur = test
        else:
            if cur:
                lines.append(cur)
            cur = w
    if cur:
        lines.append(cur)
    if not lines:
        lines = [""]
    return lines


def draw_box(c, x, y, w, h, text, fill=colors.white, stroke=colors.black,
             text_color=colors.black, font_size=8, bold=True, line_width=1.3,
             radius=7):
    c.setFillColor(fill)
    c.setStrokeColor(stroke)
    c.setLineWidth(line_width)
    c.roundRect(x, y, w, h, radius, fill=1, stroke=1)
    font_name = "Helvetica-Bold" if bold else "Helvetica"
    c.setFillColor(text_color)
    c.setFont(font_name, font_size)
    raw_lines = text.split("\n")
    all_lines = []
    for rl in raw_lines:
        if rl.strip() == "":
            all_lines.append("")
        else:
            all_lines.extend(wrap_text(rl, font_name, font_size, w - 12))
    line_h = font_size + 3
    total_h = line_h * len(all_lines)
    start_y = y + h / 2 + total_h / 2 - line_h + 2
    for i, line in enumerate(all_lines):
        lw = stringWidth(line, font_name, font_size)
        c.drawString(x + w / 2 - lw / 2, start_y - i * line_h, line)


def draw_diamond(c, cx, cy, w, h, text, fill=YELLOW_BG, font_size=8.2):
    c.setFillColor(fill)
    c.setStrokeColor(colors.black)
    c.setLineWidth(1.3)
    p = c.beginPath()
    p.moveTo(cx, cy + h / 2)
    p.lineTo(cx + w / 2, cy)
    p.lineTo(cx, cy - h / 2)
    p.lineTo(cx - w / 2, cy)
    p.close()
    c.drawPath(p, fill=1, stroke=1)
    font_name = "Helvetica-Bold"
    c.setFillColor(colors.black)
    c.setFont(font_name, font_size)
    lines = []
    for rl in text.split("\n"):
        lines.extend(wrap_text(rl, font_name, font_size, w * 0.58))
    line_h = font_size + 2.2
    total_h = line_h * len(lines)
    start_y = cy + total_h / 2 - line_h + 2
    for i, line in enumerate(lines):
        lw = stringWidth(line, font_name, font_size)
        c.drawString(cx - lw / 2, start_y - i * line_h, line)


def arrow(c, x1, y1, x2, y2, color=colors.HexColor("#333333"), width=1.5, label=None):
    c.setStrokeColor(color)
    c.setLineWidth(width)
    c.line(x1, y1, x2, y2)
    ang = math.atan2(y2 - y1, x2 - x1)
    ah_len = 7.5
    ah_ang = 0.42
    x3 = x2 - ah_len * math.cos(ang - ah_ang)
    y3 = y2 - ah_len * math.sin(ang - ah_ang)
    x4 = x2 - ah_len * math.cos(ang + ah_ang)
    y4 = y2 - ah_len * math.sin(ang + ah_ang)
    c.setFillColor(color)
    p = c.beginPath()
    p.moveTo(x2, y2)
    p.lineTo(x3, y3)
    p.lineTo(x4, y4)
    p.close()
    c.drawPath(p, fill=1, stroke=0)
    if label:
        c.setFillColor(colors.HexColor("#222222"))
        c.setFont("Helvetica-BoldOblique", 7.6)
        c.drawString((x1 + x2) / 2 + 4, (y1 + y2) / 2 + 3, label)


def draw_titled_box(c, x, y, w, h, title, body, fill, accent, title_fs=9.2,
                     body_fs=7.3, pad=7):
    c.setFillColor(fill)
    c.setStrokeColor(accent)
    c.setLineWidth(1.7)
    c.roundRect(x, y, w, h, 8, fill=1, stroke=1)
    c.setFillColor(accent)
    c.setFont("Helvetica-Bold", title_fs)
    title_lines = wrap_text(title, "Helvetica-Bold", title_fs, w - 2 * pad)
    ty = y + h - pad - title_fs
    for line in title_lines:
        lw = stringWidth(line, "Helvetica-Bold", title_fs)
        c.drawString(x + w / 2 - lw / 2, ty, line)
        ty -= title_fs + 2.5
    ty -= 2
    c.setStrokeColor(accent)
    c.setLineWidth(0.7)
    c.line(x + pad, ty, x + w - pad, ty)
    ty -= 11
    c.setFillColor(colors.HexColor("#1A1A1A"))
    for para in body.split("\n"):
        if para.strip() == "":
            ty -= body_fs * 0.7
            continue
        bold_line = para.startswith("**")
        clean = para[2:] if bold_line else para
        font = "Helvetica-Bold" if bold_line else "Helvetica"
        c.setFont(font, body_fs)
        lines = wrap_text(clean, font, body_fs, w - 2 * pad)
        for line in lines:
            c.drawString(x + pad, ty, line)
            ty -= body_fs + 2.8


def header(c, kicker, title):
    c.setFillColor(NAVY)
    c.rect(0, PAGE_H - 48, PAGE_W, 48, fill=1, stroke=0)
    c.setFillColor(colors.HexColor("#BFD4F2"))
    c.setFont("Helvetica-Bold", 9)
    c.drawString(24, PAGE_H - 16, kicker)
    c.setFillColor(colors.white)
    c.setFont("Helvetica-Bold", 16.5)
    c.drawString(24, PAGE_H - 36, title)


def footer(c, page_num, total_pages):
    c.setFillColor(GREY)
    c.setFont("Helvetica-Oblique", 7.2)
    c.drawString(24, 14, "Clinical quick-reference only - verify against current local protocols/prescribing information. Not a substitute for clinical judgment.")
    c.setFont("Helvetica-Bold", 7.5)
    c.drawRightString(PAGE_W - 24, 14, "T2DM Clinical Decision Algorithm  |  Page %d of %d" % (page_num, total_pages))


def legend(c, x, y):
    items = [(LIGHT_BLUE, BLUE, "ASCVD"), (LIGHT_PURPLE, PURPLE, "Heart Failure"),
             (LIGHT_TEAL, TEAL, "CKD"), (LIGHT_ORANGE, ORANGE, "Obesity"),
             (LIGHT_RED, RED, "Avoid / Caution")]
    cx = x
    for fill, accent, label in items:
        c.setFillColor(fill)
        c.setStrokeColor(accent)
        c.setLineWidth(1.1)
        c.rect(cx, y, 10, 10, fill=1, stroke=1)
        c.setFillColor(colors.HexColor("#222222"))
        c.setFont("Helvetica", 7.6)
        c.drawString(cx + 14, y + 2, label)
        cx += 14 + stringWidth(label, "Helvetica", 7.6) + 16


def draw_table(c, x, top_y, col_widths, rows, header_fs=8.4, body_fs=7.2):
    total_w = sum(col_widths)
    y_cursor = top_y
    for r_idx, row in enumerate(rows):
        is_header = (r_idx == 0)
        fs = header_fs if is_header else body_fs
        font = "Helvetica-Bold" if is_header else "Helvetica"
        cell_lines = []
        max_lines = 1
        for ci, cell in enumerate(row):
            lines = []
            for para in str(cell).split("\n"):
                lines.extend(wrap_text(para, font, fs, col_widths[ci] - 10))
            cell_lines.append(lines)
            max_lines = max(max_lines, len(lines))
        row_h = max_lines * (fs + 3.2) + 10
        fill = NAVY if is_header else (LIGHT_GREY if r_idx % 2 == 0 else colors.white)
        c.setFillColor(fill)
        c.rect(x, y_cursor - row_h, total_w, row_h, fill=1, stroke=0)
        c.setStrokeColor(colors.HexColor("#9AA7B8"))
        c.setLineWidth(0.6)
        c.rect(x, y_cursor - row_h, total_w, row_h, fill=0, stroke=1)
        cx = x
        text_color = colors.white if is_header else colors.HexColor("#1A1A1A")
        for ci, lines in enumerate(cell_lines):
            c.setStrokeColor(colors.HexColor("#9AA7B8"))
            c.line(cx, y_cursor - row_h, cx, y_cursor)
            c.setFillColor(text_color)
            c.setFont(font, fs)
            ty = y_cursor - 7 - fs
            for line in lines:
                c.drawString(cx + 5, ty, line)
                ty -= fs + 3.2
            cx += col_widths[ci]
        c.setStrokeColor(colors.HexColor("#9AA7B8"))
        c.line(cx, y_cursor - row_h, cx, y_cursor)
        y_cursor -= row_h
    return y_cursor


def section_title(c, x, y, text, color=NAVY, fs=11.5):
    c.setFillColor(color)
    c.setFont("Helvetica-Bold", fs)
    c.drawString(x, y, text)


# ==================================================================
c = canvas.Canvas(OUT, pagesize=landscape(LETTER))
TOTAL_PAGES = 4

# ------------------------------------------------------------------
# PAGE 1 - Comorbidity-driven pathway
# ------------------------------------------------------------------
header(c, "TYPE 2 DIABETES MELLITUS - OUTPATIENT ALGORITHM (PART 1 of 2)", "Comorbidity-Driven First-Line Therapy")

start_w, start_h = 260, 44
start_x = PAGE_W / 2 - start_w / 2
start_y = 500
draw_box(c, start_x, start_y, start_w, start_h,
         "ALL PATIENTS WITH NEW/EXISTING T2DM\nLifestyle modification + METFORMIN\n(unless eGFR <30 or contraindicated)",
         fill=LIGHT_GREY, stroke=NAVY, text_color=NAVY, font_size=8.6)

dia_cx, dia_cy, dia_w, dia_h = PAGE_W / 2 - 40, 430, 280, 72
arrow(c, dia_cx, start_y, dia_cx, dia_cy + dia_h / 2 + 2)
draw_diamond(c, dia_cx, dia_cy, dia_w, dia_h,
             "Compelling comorbidity present?\n(ASCVD, Heart Failure, CKD, or Obesity as priority)")

# NO branch -> side box pointing to page 2
no_x, no_y, no_w, no_h = 600, dia_cy - 30, 165, 62
arrow(c, dia_cx + dia_w / 2, dia_cy, no_x, no_y + no_h / 2, label="NO")
draw_box(c, no_x, no_y, no_w, no_h,
         "No compelling comorbidity\n\nGo to PAGE 2:\nStandard Escalation Ladder",
         fill=LIGHT_GREY, stroke=GREY, text_color=colors.HexColor("#222222"), font_size=8)

# YES branch -> 4 cards
card_y, card_h, card_w, gap = 165, 165, 175, 20
total_row_w = 4 * card_w + 3 * gap
row_x0 = PAGE_W / 2 - total_row_w / 2 - 40
positions = [row_x0 + i * (card_w + gap) for i in range(4)]

arrow(c, dia_cx - 20, dia_cy - dia_h / 2, dia_cx - 20, card_y + card_h + 28, label="YES")
# fan lines to each card
for px in positions:
    arrow(c, dia_cx - 20, card_y + card_h + 28, px + card_w / 2, card_y + card_h + 2)

draw_titled_box(c, positions[0], card_y, card_w, card_h, "ASCVD / High ASCVD Risk",
                "**PREFERRED:\nSGLT2 inhibitor and/or GLP-1 RA with proven CV benefit - "
                "regardless of A1c or metformin use.\n\n**CONTINUE:\nMetformin if tolerated/not contraindicated.",
                LIGHT_BLUE, BLUE)

draw_titled_box(c, positions[1], card_y, card_w, card_h, "Heart Failure (esp. HFrEF)",
                "**PREFERRED:\nSGLT2 inhibitor - first-line regardless of A1c/metformin. "
                "Reduces HF hospitalization.\n\n**AVOID:\nPioglitazone (fluid retention); caution with saxagliptin.",
                LIGHT_PURPLE, PURPLE)

draw_titled_box(c, positions[2], card_y, card_w, card_h, "CKD / Albuminuria",
                "**PREFERRED:\nMetformin (dose-adjust; stop <30 eGFR) + SGLT2i "
                "(renal benefit continues to ~eGFR 20).\n\n**ADD-ON:\nIf albuminuria persists and K+ normal - Finerenone (nonsteroidal MRA).",
                LIGHT_TEAL, TEAL)

draw_titled_box(c, positions[3], card_y, card_w, card_h, "Obesity Is the Priority",
                "**PREFERRED:\nGLP-1 RA or dual GIP/GLP-1 RA (tirzepatide) - greatest weight-loss efficacy.\n\n"
                "**AVOID (early):\nSulfonylureas, TZDs, insulin (weight gain).",
                LIGHT_ORANGE, ORANGE)

# bottom note
note_y, note_h = 40, 78
note_x, note_w = 16, PAGE_W - 32
draw_box(c, note_x, note_y, note_w, note_h,
         "ALL COMORBIDITY PATHWAYS: Reassess in ~3 months. If not at individualized A1c goal, add another "
         "comorbidity-appropriate agent (do not stack two insulin secretagogues). If glucose remains uncontrolled "
         "after combination therapy, proceed to insulin initiation - see PAGE 2 for the escalation ladder.",
         fill=colors.white, stroke=colors.HexColor("#999999"), text_color=colors.HexColor("#222222"),
         font_size=8.2, bold=False, line_width=1)

footer(c, 1, TOTAL_PAGES)
c.showPage()

# ------------------------------------------------------------------
# PAGE 2 - Standard escalation ladder + insulin initiation
# ------------------------------------------------------------------
header(c, "TYPE 2 DIABETES MELLITUS - OUTPATIENT ALGORITHM (PART 2 of 2)", "Standard Escalation Ladder & Insulin Initiation")

chain_x, chain_w = 40, 430
steps = [
    ("STEP 1", "Metformin + lifestyle\n(no compelling comorbidity)", LIGHT_GREY, NAVY),
    ("STEP 2", "Add 2nd agent: SGLT2 inhibitor or GLP-1 RA preferred\n(or DPP-4i / sulfonylurea / TZD by cost/access)", LIGHT_BLUE, BLUE),
    ("STEP 3", "Reassess ~3 months - not at goal?\nAdd 3rd agent with a DIFFERENT mechanism", LIGHT_TEAL, TEAL),
    ("STEP 4", "Still not at goal?\nStart BASAL INSULIN at bedtime\n(keep metformin/SGLT2i/GLP-1RA; taper SU/DPP-4i)", LIGHT_PURPLE, PURPLE),
    ("STEP 5", "Fasting glucose OK but daytime spikes?\nAdd prandial insulin at largest meal (\"basal-plus\") or premixed insulin", LIGHT_ORANGE, ORANGE),
    ("STEP 6", "Still uncontrolled?\nFULL BASAL-BOLUS regimen\n(long-acting + rapid-acting before every meal)", LIGHT_RED, RED),
]

y_top = 500
box_h = 68
gap_v = 18
for i, (tag, text, fill, accent) in enumerate(steps):
    y = y_top - i * (box_h + gap_v)
    draw_box(c, chain_x, y - box_h, chain_w, box_h, tag + "\n" + text,
             fill=fill, stroke=accent, text_color=colors.HexColor("#1A1A1A"), font_size=8.3)
    if i > 0:
        prev_y = y_top - (i - 1) * (box_h + gap_v) - box_h
        arrow(c, chain_x + chain_w / 2, prev_y, chain_x + chain_w / 2, y)

# side callout: hypoglycemia + de-intensification (spans right column)
side_x = chain_x + chain_w + 55
side_w = PAGE_W - side_x - 24

draw_titled_box(c, side_x, 330, side_w, 190, "AT ANY STEP: Recurrent Hypoglycemia",
                "**De-intensify first:\nDrop sulfonylurea or meglitinide before other agents - "
                "these carry the highest hypoglycemia risk.\n\n"
                "**Relax targets:\nConsider a higher individualized A1c goal (e.g. ~8%) in elderly, frail, "
                "or multimorbid patients, or those with limited life expectancy.\n\n"
                "**Consider CGM:\nContinuous glucose monitoring helps detect patterns and titrate safely.",
                LIGHT_RED, RED, title_fs=10.5, body_fs=8.3)

draw_titled_box(c, side_x, 120, side_w, 175, "2025 Practice Shift to Note",
                "Recent ADA Standards of Care favor **EARLY COMBINATION THERAPY** "
                "(e.g., metformin + SGLT2i/GLP-1 RA together at diagnosis in high-risk patients) "
                "rather than waiting for metformin monotherapy to \"fail\" before adding a second agent.\n\n"
                "Comorbidity-driven agent selection (Page 1) now takes priority over the A1c number itself "
                "when ASCVD, HF, or CKD is present.",
                LIGHT_BLUE, NAVY, title_fs=10.5, body_fs=8.3)

footer(c, 2, TOTAL_PAGES)
c.showPage()

# ------------------------------------------------------------------
# PAGE 3 - Quick reference tables
# ------------------------------------------------------------------
header(c, "QUICK-REFERENCE TABLES", "Escalation Cascade & Comorbidity Cheat-Sheet")

section_title(c, 20, PAGE_W * 0 + 545, "If Sugar Remains High Despite Current Regimen - What To Add / Replace")
esc_rows = [
    ["Current Regimen", "Sugar Still High -> Next Step"],
    ["Lifestyle alone", "Add metformin (unless eGFR <30 or contraindicated)"],
    ["Metformin alone, above goal", "Add SGLT2i or GLP-1 RA (comorbidity-driven) or another 2nd agent"],
    ["Metformin + 1 agent, uncontrolled", "Add a 3rd class with a complementary mechanism (avoid stacking two secretagogues)"],
    ["Triple therapy failing", "Start basal insulin at bedtime; continue metformin/SGLT2i/GLP-1RA; taper SU/DPP-4i"],
    ["Basal insulin + orals, fasting OK but daytime spikes", "Add prandial insulin at the largest meal (\"basal-plus\") or premixed insulin AM/PM"],
    ["Basal-plus insulin still failing", "Convert to full basal-bolus (long-acting + rapid-acting before each meal)"],
    ["Basal-bolus, high doses (>1-1.5 U/kg/day), still uncontrolled", "Suspect severe insulin resistance - add pioglitazone (watch HF/edema) or maximize GLP-1RA/SGLT2i; recheck adherence, technique, steroids, infection"],
    ["Any regimen + recurrent hypoglycemia", "De-intensify: drop sulfonylurea/meglitinide first; relax A1c goal if elderly/frail"],
]
col_widths_1 = [230, 530]
bottom1 = draw_table(c, 20, 542, col_widths_1, esc_rows)

section_title(c, 20, bottom1 - 14, "Comorbidity-Driven Drug Selection Cheat-Sheet")
com_rows = [
    ["Comorbidity", "Preferred", "Avoid / Caution"],
    ["ASCVD / high CV risk", "GLP-1 RA or SGLT2i with proven CV benefit", "-"],
    ["Heart Failure (HFrEF)", "SGLT2i first-line regardless of A1c", "Pioglitazone; caution with saxagliptin"],
    ["CKD / albuminuria", "Metformin (dose-adjust) + SGLT2i; add finerenone if albuminuria persists (K+ normal)", "Metformin if eGFR <30"],
    ["Obesity as priority", "GLP-1 RA or dual GIP/GLP-1 RA (tirzepatide)", "Sulfonylureas, TZDs, insulin as early add-on"],
    ["Elderly / frail", "DPP-4 inhibitor; simplified insulin regimens; cautious SGLT2i (volume depletion)", "Long-acting sulfonylureas (e.g. glyburide)"],
    ["Hepatic impairment", "Insulin is safest", "Metformin (significant disease); sulfonylureas; monitor LFTs with pioglitazone"],
    ["History of pancreatitis", "-", "GLP-1 RA, DPP-4i (theoretical association)"],
]
col_widths_2 = [150, 320, 290]
bottom2 = draw_table(c, 20, bottom1 - 20, col_widths_2, com_rows)

footer(c, 3, TOTAL_PAGES)
c.showPage()

# ------------------------------------------------------------------
# PAGE 4 - Inpatient protocol
# ------------------------------------------------------------------
header(c, "TYPE 2 DIABETES MELLITUS - INPATIENT PROTOCOL", "Ward, ICU, Perioperative & Hyperglycemic Emergencies")

adm_x, adm_y, adm_w, adm_h = PAGE_W / 2 - 150, 500, 300, 44
draw_box(c, adm_x, adm_y, adm_w, adm_h,
         "HOSPITALIZED PATIENT WITH HYPERGLYCEMIA\nInsulin is the cornerstone - oral agents unreliable in acute illness",
         fill=LIGHT_GREY, stroke=NAVY, text_color=NAVY, font_size=8.6)

dia2_cx, dia2_cy, dia2_w, dia2_h = PAGE_W / 2, 430, 230, 66
arrow(c, adm_x + adm_w / 2, adm_y, dia2_cx, dia2_cy + dia2_h / 2 + 2)
draw_diamond(c, dia2_cx, dia2_cy, dia2_w, dia2_h, "Critically ill / ICU?", font_size=9)

left_x, right_x = 90, PAGE_W - 90 - 300
box_y, box_h2, box_w2 = 300, 130, 300

arrow(c, dia2_cx - dia2_w / 2, dia2_cy, left_x + box_w2 / 2, box_y + box_h2, label="NO")
draw_titled_box(c, left_x, box_y, box_w2, box_h2, "Non-Critically Ill Ward Patient (Eating)",
                "**Regimen:\nBasal-bolus + correction insulin (NOT sliding-scale alone - inferior per RCT evidence).\n\n"
                "**Target:\n140-180 mg/dL for most patients.\n\n"
                "**Alternative for mild hyperglycemia:\nDPP-4 inhibitor + correction insulin (non-T1DM).\n\n"
                "**Home insulin pump/hybrid closed-loop:\nMay continue if patient/team capable.",
                LIGHT_BLUE, BLUE, body_fs=7.6)

arrow(c, dia2_cx + dia2_w / 2, dia2_cy, right_x + box_w2 / 2, box_y + box_h2, label="YES")
draw_titled_box(c, right_x, box_y, box_w2, box_h2, "Critically Ill / ICU Patient",
                "**Regimen:\nVariable-rate IV insulin infusion - preferred for rapidly changing hemodynamics/nutrition.\n\n"
                "**Target:\n140-180 mg/dL (ADA 2025 / SCCM 2024 / ACP).\n\n"
                "**Start/intensify:\nWhen glucose persistently >180 mg/dL.\n\n"
                "**Avoid <140 mg/dL target:\nIncreases hypoglycemia risk without added benefit.",
                LIGHT_PURPLE, PURPLE, body_fs=7.6)

# perioperative + emergencies row
peri_y, peri_h, peri_w = 40, 235, 250
peri_x = 40
draw_titled_box(c, peri_x, peri_y, peri_w, peri_h, "Perioperative Management",
                "**HbA1c >8%:\nConsider delaying elective surgery (linked to wound infection/mortality).\n\n"
                "**Fasting insulin dose:\nReduce stable home dose by 1/3 to 1/2.\n\n"
                "**SGLT2 inhibitors:\nSTOP 3-4 days pre-op - risk of euglycemic DKA (FDA warning).\n\n"
                "**Insulin pump:\nMay continue in OR if team trained; check glucose >= hourly.\n\n"
                "**ERAS carb drinks:\nUp to 2h pre-op reduce catabolism/hypoglycemia risk.",
                LIGHT_TEAL, TEAL, body_fs=7.3)

dka_x = peri_x + peri_w + 20
draw_titled_box(c, dka_x, peri_y, peri_w, peri_h, "Diabetic Ketoacidosis (DKA)",
                "Can occur in T2DM under severe stress (infection, MI, missed insulin).\n\n"
                "**Core therapy:\nIV isotonic fluids -> insulin infusion (~0.1 U/kg/h) -> "
                "REPLACE POTASSIUM before/with insulin (insulin drives K+ intracellularly) -> "
                "treat underlying trigger.\n\n"
                "**Location:\nICU / intermediate care with continuous monitoring.",
                LIGHT_ORANGE, ORANGE, body_fs=7.3)

hhs_x = dka_x + peri_w + 20
draw_titled_box(c, hhs_x, peri_y, peri_w, peri_h, "Hyperosmolar Hyperglycemic State (HHS)",
                "Classic T2DM presentation - elderly, no significant ketosis, markedly elevated osmolality.\n\n"
                "**Core therapy:\nAggressive fluid resuscitation is the PRIORITY.\n"
                "Low-dose insulin (~0.05 U/kg/h) only if significant ketonemia present.\n\n"
                "**Caution:\nCorrect slowly - avoid rapid osmotic shifts / cerebral edema.",
                LIGHT_RED, RED, body_fs=7.3)

footer(c, 4, TOTAL_PAGES)
c.showPage()

c.save()
print("Saved:", OUT)
Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.