"""Daniel's pediatric fracture eponyms guide, as a new article."""
import uuid
from datetime import datetime

from app.database import SessionLocal
from app.models.article import Article
from app.services import article_service

SHORT = [
("The table worth memorising", """- **Salter-Harris**: physeal injuries I–V, classified by what the fracture line crosses. ==Type II is the commonest (>70%); Type V has the worst growth prognosis and the most normal-looking first film.==
- **Monteggia**: proximal ulnar fracture + radial head dislocation. ==The radiocapitellar line must hit the capitellum on every view.==
- **Galeazzi**: distal radial shaft fracture + DRUJ disruption — ==in a child, often a distal ulnar physeal separation instead==.
- **Tillaux**: adolescent ==Salter-Harris III== avulsion of the anterolateral distal tibial epiphysis by the AITFL.
- **Triplane**: adolescent ==Salter-Harris IV equivalent== across sagittal, coronal and transverse planes.
- **Chance**: flexion-distraction of the thoracolumbar spine. ==Up to 50% have a hollow viscus injury.==
- **Segond**: lateral tibial plateau avulsion, ==pathognomonic of ACL rupture (75–100%)==.
- **Maisonneuve**: proximal fibular fracture with syndesmotic and medial ankle disruption.
- **Bennett / Rolando**: intra-articular base-of-thumb-metacarpal fractures, two-part versus comminuted.
- **Jones**: ==watershed== metaphyseal–diaphyseal fracture of the 5th metatarsal, high nonunion risk."""),

("The pediatric traps", """- A ==plastically bowed or greenstick ulna== hides the radial head dislocation of a Monteggia. Missed, it becomes chronic subluxation, valgus elbow, and late ulnar nerve palsy.
- The thumb metacarpal physis is ==proximal==, unlike the other four. So young children get Salter-Harris II fractures of the base, not true Bennett or Rolando patterns.
- The 5th metatarsal apophysis (ages 9–14) lies ==parallel to the shaft==; a fracture runs ==across== it.
- ==Every medial ankle injury needs the proximal fibula examined and imaged== — that is how a Maisonneuve is caught.
- A ==seatbelt sign== on the abdomen after a lap-belt collision means imaging the abdomen and immobilising the spine.
- Tillaux and Triplane both need ==CT==: plain films underestimate the articular step-off, and ==> 2 mm displacement== is operative."""),
]

LONG = [
("Why eponyms survive", """Eponymous fracture designations are deeply woven into the lexicon of orthopedic surgery, pediatric medicine, and emergency care. While modern trauma classifications increasingly rely on descriptive anatomical terms, eponyms remain rapid shorthand for complex injury patterns, mechanism profiles, and predictable pitfalls.

In pediatric patients the presence of the physis, thick periosteum, and progressive skeletal maturation alters the behavior of these classic fractures compared with their adult counterparts. What follows is the major eponyms encountered in pediatric and adolescent care: the clinicians behind them, the anatomy, and what changes when the patient is still growing."""),

("Salter-Harris: the classification masterwork", """Technically a classification rather than a single fracture, and no discussion of pediatric fracture terminology is complete without it. Dr Robert Bruce Salter, a Canadian orthopedic pioneer at the Hospital for Sick Children in Toronto, and Dr W. Robert Harris published their five-part scheme in 1963, based on the mechanism of injury and the relationship of the fracture line to the growing physeal zones.

- **Type I**: pure separation through the physis, typically the zone of hypertrophy. Radiographs may appear normal aside from soft-tissue swelling; tenderness directly over the physis is diagnostic. Excellent prognosis with closed reduction and casting.
- **Type II**: through the physis, exiting via a triangular metaphyseal fragment — the Thurston Holland sign. The most common physeal injury pattern, over 70%. Remodeling potential is high.
- **Type III**: intra-articular, traversing the epiphysis and running along the physis before exiting the joint. Requires anatomical reduction to prevent joint incongruity and premature physeal arrest.
- **Type IV**: intra-articular, crossing the epiphysis, the full thickness of the physis, and out through the metaphysis. High risk of bony bridge formation; often needs open reduction and internal fixation.
- **Type V**: severe axial crush destroying the germinal zone. Initial radiographs are often deceptively normal or show subtle physeal narrowing. The highest risk of growth arrest and angular deformity."""),

("Monteggia fracture-dislocation", """Named after Giovanni Battista Monteggia, an Italian surgeon who described the pattern in 1814, before clinical radiography existed. He documented a proximal third ulnar shaft fracture with anterior dislocation of the radial head.

**Pathoanatomy.** High-energy or indirect fall on an outstretched hand with forced pronation or hyperpronation.

**Bado classification.** Type I, anterior dislocation of the radial head — the commonest in children. Type II, posterior. Type III, lateral or anterolateral, common in younger children with a greenstick ulnar fracture. Type IV, fracture of both radius and ulna with anterior radial head dislocation.

**Pediatric considerations.** Plastic deformation (bowing) or a subtle greenstick fracture of the ulna easily leads a clinician to overlook the associated radial head dislocation. A missed Monteggia injury leads to chronic radial head subluxation, valgus elbow deformity, and late-onset ulnar nerve palsy.

**The rule.** On any forearm or elbow radiograph, a line drawn through the center of the radial shaft and head — the radiocapitellar line — must intersect the capitellum in all projections.

**Management.** Closed reduction succeeds in the majority of acute pediatric cases: stabilise the ulna and the radial head follows. Operative management is reserved for unstable or irreducible injuries."""),

("Galeazzi fracture-dislocation", """Identified by Dr Riccardo Galeazzi, an Italian surgeon at the Istituto dei Rachitici in Milan, who analysed a large series in 1934. Sometimes called the reverse Monteggia.

**Pathoanatomy.** Fracture of the distal third of the radial shaft with disruption of the distal radioulnar joint (DRUJ) and rupture of the triangular fibrocartilage complex.

**Pediatric variant (Galeazzi-equivalent).** Because children have open distal radial physes, the force may produce a distal radial metaphyseal fracture with an ulnar physeal separation — Salter-Harris I or II of the distal ulna — rather than pure ligamentous disruption of the DRUJ.

**Management.** Unlike adults, where rigid plate fixation is mandatory, pediatric Galeazzi fractures can frequently be managed with anatomical closed reduction and long-arm casting in supination, provided the DRUJ is stable."""),

("Capitellar fractures: Hahn-Steinthal and Kocher-Lorenz", """Isolated fractures of the humeral capitellum are rare in young children, who more commonly sustain lateral condyle fractures, but occur in older adolescents near skeletal maturity.

- **Hahn-Steinthal**, described by Ludwig Hahn (1853) and Carl Steinthal (1898). A Type I capitellar fracture: a large, complete osseous fragment involving substantial subchondral trabecular bone and occasionally part of the trochlea.
- **Kocher-Lorenz**, named after the Swiss Nobel laureate Emil Theodor Kocher and the Austrian orthopedic surgeon Adolf Lorenz. A Type II capitellar fracture: an avulsion or shear injury of only the articular cartilage shell with a sliver of subchondral bone — the "articular rind".

**Management.** Hahn-Steinthal patterns usually require ORIF with headless compression screws. Kocher-Lorenz fragments, if unfixable because of their size, may need arthroscopic excision or chondral pinning."""),

("Distal radius: Colles, Smith, Barton and Chauffeur", """Prevalent across all ages, and defining specific patterns near the distal radius.

- **Colles** (Abraham Colles, 1814): metaphyseal distal radius fracture with dorsal displacement and dorsal angulation — the dinner fork deformity. In children this is often a complete metaphyseal fracture or a Salter-Harris II injury.
- **Smith** (Robert William Smith, 1847): the reverse Colles. Volar displacement and volar angulation of the distal radial fragment, the garden spade deformity, from a direct blow to the dorsum of the flexed wrist or a fall onto a flexed hand.
- **Barton** (John Rhea Barton, 1838): fracture-dislocation of the radiocarpal joint by an intra-articular shearing mechanism, involving either the dorsal rim (classic) or the volar rim. Intrinsically unstable; needs anatomical reduction.
- **Chauffeur (Hutchinson)**: named for the injury sustained when a hand crank backfired against the wrist of an early motorist. An isolated intra-articular fracture of the radial styloid, from avulsion under traction of the radioscaphocapitate ligament or direct compression by the scaphoid."""),

("Hand: Bennett and Rolando", """Injuries to the base of the thumb metacarpal cause profound loss of opposition and grip strength if inadequately stabilised.

- **Bennett** (Edward Hallaran Bennett, an Irish anatomist and surgeon, 1882): an intra-articular two-piece fracture-subluxation of the base of the first metacarpal. The small anterior/medial triangular fragment stays anchored to the trapezium by the anterior oblique (beak) ligament, while the larger distal shaft is displaced proximally, radially and dorsally by the uninhibited pull of abductor pollicis longus.
- **Rolando** (Silvio Rolando, 1910): a comminuted, intra-articular, three-part or multi-part T- or Y-shaped fracture at the same base. Highly unstable, with a worse prognosis than a simple Bennett.

**Pediatric considerations.** In younger children the physis of the first metacarpal is at its *proximal* end, unlike the 2nd–5th which have distal physes. True Bennett and Rolando intra-articular injuries are therefore uncommon in young children, who instead sustain Salter-Harris II extra-articular physeal fractures of the thumb metacarpal base. The intra-articular patterns appear in mid-to-late adolescence."""),

("Spine: the Chance fracture", """Identified by the British radiologist Dr George Quentin Chance in 1948, and classic in the pediatric population.

**Pathoanatomy.** A pure flexion-distraction injury across the thoracolumbar junction, most commonly T12–L2. The axis of flexion rotates around an anterior fulcrum, so tension failure distracts the posterior and middle columns while the anterior column is compressed.

**Clinical context.** The classic seatbelt fracture: a motor vehicle collision in which a child is restrained by an abdominal lap belt with no shoulder harness.

**High-yield association.** Concomitant intra-abdominal hollow viscus injury — small bowel perforation, mesenteric tear, duodenal hematoma — occurs in up to 50% of pediatric cases. An abdominal wall contusion, the seatbelt sign, mandates urgent cross-sectional abdominal imaging and spine immobilisation."""),

("Adolescent ankle: Tillaux and Triplane", """The distal tibial physis does not close uniformly. It fuses over an 18-month window during adolescence — roughly 12–15 years in girls, 13–16 in boys — beginning centrally, moving medially, and finishing anterolaterally. This transitional window produces two fracture patterns that exist only during it.

**Tillaux.** First noted experimentally by the French anatomist Paul Jules Tillaux in 1872 and later characterised radiographically by Henri Chaput, hence Tillaux-Chaput. Forced external rotation of the foot on the leg makes the anterior inferior tibiofibular ligament pull on the anterolateral distal tibial epiphysis; because the medial physis has already fused, the open anterolateral part avulses — a Salter-Harris III intra-articular fracture. Plain films underestimate displacement, so CT is essential to assess the articular step-off; more than 2 mm needs open or arthroscopically assisted reduction and fixation to prevent post-traumatic osteoarthritis.

**Triplane (Marmor-Lynn).** Elaborated by Leonard Marmor (1970) and G. E. Lynn (1972), in the same transitional age group. A three-dimensional, multiplanar fracture behaving as a Salter-Harris IV equivalent: a sagittal intra-articular epiphyseal split (like a Type III), an axial component through the open physis (like a Type I), and a coronal metaphyseal spike extending posteriorly (like a Type II). It presents with two, three or four fragments; CT reconstruction is the diagnostic gold standard, and more than 2 mm of articular displacement or translation requires anatomical reduction with screws placed strictly parallel to, or avoiding, the open parts of the physis."""),

("Lower limb and foot", """**Maisonneuve** (Jacques Gilles Maisonneuve, a student of Dupuytren, 1840). A spiral fracture of the proximal third of the fibula with disruption of the distal tibiofibular syndesmosis, rupture of the deltoid ligament or avulsion of the medial malleolus, and a tear of the interosseous membrane up to the level of the fibular break. Every child or adolescent with an apparently isolated medial ankle sprain or medial malleolar fracture must have the proximal fibula and knee examined and imaged, or this high-grade syndesmotic disruption is missed. See also [[128|ankle sprain]].

**Bosworth** (David M. Bosworth, 1947). A severe, irreducible fracture-dislocation in which the distal fibular fragment is displaced and trapped behind the posterior tubercle of the distal tibia. Closed reduction is virtually impossible because the fibular shaft is incarcerated behind the bony shelf, and attempted manipulation risks neurovascular compromise or skin necrosis. It needs emergent open reduction.

**Segond** (Paul Segond, 1879). An avulsion of the anterolateral margin of the lateral tibial plateau, just posterior to Gerdy's tubercle, by traction of the anterolateral ligament during internal rotation and varus loading. The fragment itself is trivial; what matters is that it is pathognomonic of major intra-articular derangement — ACL rupture in 75–100% of cases, with associated lateral meniscal tears.

**Jones versus pseudo-Jones.** Sir Robert Jones described his in 1902, having sustained it while dancing. A *true Jones* fracture is transverse, at the metaphyseal–diaphyseal junction of the base of the fifth metatarsal, 1.5–3 cm distal to the tuberosity — a vascular watershed between the intramedullary and periosteal supplies, and therefore notorious for delayed union, nonunion and refracture; it often needs non-weightbearing immobilisation or an intramedullary screw. A *pseudo-Jones* (dancer's, or tuberosity avulsion) fracture is through the tuberosity or apophysis, proximal to the Jones zone, from inversion in plantarflexion, avulsed by the lateral band of the plantar fascia — historically blamed on peroneus brevis alone. Its blood supply is excellent and it heals reliably in a stiff-soled shoe or walking boot.

**The pediatric pitfall.** Do not mistake the normal apophysis of the fifth metatarsal for a fracture. It appears between ages 9 and 14 and lies *parallel* to the shaft; true avulsion and Jones fractures run *transversely or obliquely* across the bone."""),
]

SUMMARY = ("The eponyms still used at the bedside — Salter-Harris, Monteggia, Galeazzi, Tillaux, Triplane, Chance, Segond, "
           "Maisonneuve, Bennett, Rolando, Jones — with the anatomy behind each, the clinician who named it, and what "
           "changes when the patient still has open physes and a thick periosteum.")

INTRO = """A working guide to the fracture names that carry a mechanism, a pitfall and a management plan inside them — and to how each behaves differently in a growing skeleton.

*By Daniel Onyejesi — pediatric orthopedics.*"""


def build(rows, variant):
    return [{
        "id": uuid.uuid4().hex,
        "slug": (title.lower().replace(":", "").replace(",", "").replace("'", "")
                      .replace("(", "").replace(")", "").replace("/", "-")
                      .replace(" ", "-")[:120].strip("-")),
        "title": title,
        "variant": variant,
        "content": content.strip(),
    } for title, content in rows]


db = SessionLocal()
existing = db.query(Article).filter(Article.slug == "pediatric-fracture-eponyms").first()
article = existing or Article(slug="pediatric-fracture-eponyms")
article.title = "Pediatric Fracture Eponyms"
article.summary = SUMMARY
article.content = INTRO
article.sections = build(SHORT, "short") + build(LONG, "long")
article.references_json = [{"title": "Kliegman R. Nelson Textbook of Pediatrics", "author": None, "pages": []}]
article.category_id = 14888
article.user_id = 6
article.status = "published"
article.first_published_at = article.first_published_at or datetime.utcnow()
if not existing:
    db.add(article)
db.commit()
db.refresh(article)
article_service.reindex(db, article)
print("eponyms:", article.id, article.slug, len(article.sections), "sections",
      article_service.available_variants(article))
