formal-ai 0.231.0

Formal symbolic AI implementation with OpenAI-compatible APIs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Curated program bodies used by composite `write_program` blueprints.
//!
//! Keeping longer bodies outside `blueprint.rs` preserves the repository's
//! file-size limit while leaving recipe selection and rendering in one place.

pub(super) const RUST_HTTP_JSON_STATS: &str = r#"//! Fetch JSON from a URL and report the mean and median of every number in it.
//!
//! Cargo.toml dependencies:
//!   reqwest = { version = "0.12", features = ["blocking", "json"] }
//!   serde_json = "1"

use std::env;
use std::error::Error;

use serde_json::Value;

/// Recursively collect every numeric value out of a decoded JSON document,
/// regardless of how deeply it is nested inside arrays or objects.
fn collect_numbers(value: &Value, numbers: &mut Vec<f64>) {
    match value {
        Value::Number(number) => {
            if let Some(as_float) = number.as_f64() {
                numbers.push(as_float);
            }
        }
        Value::Array(items) => items.iter().for_each(|item| collect_numbers(item, numbers)),
        Value::Object(map) => map.values().for_each(|item| collect_numbers(item, numbers)),
        _ => {}
    }
}

/// Arithmetic mean of the samples (the caller guarantees a non-empty slice).
fn mean(samples: &[f64]) -> f64 {
    samples.iter().sum::<f64>() / samples.len() as f64
}

/// Median of the samples; averages the two middle values when the count is even.
fn median(samples: &mut [f64]) -> f64 {
    samples.sort_by(|left, right| left.partial_cmp(right).expect("no NaN in input"));
    let middle = samples.len() / 2;
    if samples.len() % 2 == 0 {
        (samples[middle - 1] + samples[middle]) / 2.0
    } else {
        samples[middle]
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    // 1. Read the target URL from the first command-line argument.
    let url = env::args()
        .nth(1)
        .ok_or("usage: stats <url-returning-json>")?;

    // 2. Make the HTTP GET request and parse the JSON body. Both steps can fail,
    //    so `?` propagates any network or decoding error up to `main`.
    let document: Value = reqwest::blocking::get(&url)?.json()?;

    // 3. Gather every number from the decoded document.
    let mut numbers = Vec::new();
    collect_numbers(&document, &mut numbers);
    // region:error_handling
    // Guard against an empty data set before computing statistics.
    if numbers.is_empty() {
        return Err("the JSON response contained no numbers".into());
    }
    // endregion:error_handling

    // 4. Compute and print the statistics.
    println!("count:  {}", numbers.len());
    println!("mean:   {:.4}", mean(&numbers));
    println!("median: {:.4}", median(&mut numbers));
    Ok(())
}
"#;

pub(super) const PYTHON_HTTP_JSON_STATS: &str = r#""""Fetch JSON from a URL and report the mean and median of every number in it.

Dependencies:  pip install requests
"""

import statistics
import sys

import requests


def collect_numbers(value):
    """Recursively collect every int/float out of a decoded JSON value."""
    # bool subclasses int, so skip it explicitly
    if isinstance(value, bool):
        return []
    if isinstance(value, (int, float)):
        return [float(value)]
    if isinstance(value, list):
        return [number for item in value for number in collect_numbers(item)]
    if isinstance(value, dict):
        return [number for item in value.values() for number in collect_numbers(item)]
    return []


def main():
    # 1. Read the target URL from the first command-line argument.
    if len(sys.argv) < 2:
        raise SystemExit("usage: stats.py <url-returning-json>")
    url = sys.argv[1]

    # 2. Make the HTTP GET request and parse the JSON body.
    response = requests.get(url, timeout=30)
    # region:error_handling
    # Turn any non-2xx HTTP status into an exception before decoding.
    response.raise_for_status()
    # endregion:error_handling
    document = response.json()

    # 3. Gather every number from the decoded JSON.
    numbers = collect_numbers(document)
    # region:error_handling
    if not numbers:
        raise SystemExit("the JSON response contained no numbers")
    # endregion:error_handling

    # 4. Compute and print the statistics.
    print(f"count:  {len(numbers)}")
    print(f"mean:   {statistics.mean(numbers):.4f}")
    print(f"median: {statistics.median(numbers):.4f}")


if __name__ == "__main__":
    main()
"#;

pub(super) const JAVASCRIPT_HTTP_JSON_STATS: &str = r#"// Fetch JSON from a URL and report the mean and median of every number in it.
//
// Requirements: Node.js 18+ (built-in global fetch; no extra packages).

// Recursively collect every finite number out of a decoded JSON value.
function collectNumbers(value) {
  if (typeof value === "number" && Number.isFinite(value)) return [value];
  if (Array.isArray(value)) return value.flatMap(collectNumbers);
  if (value && typeof value === "object") {
    return Object.values(value).flatMap(collectNumbers);
  }
  return [];
}

// Arithmetic mean of the samples (the caller guarantees a non-empty array).
function mean(samples) {
  return samples.reduce((total, sample) => total + sample, 0) / samples.length;
}

// Median of the samples; averages the two middle values for an even count.
function median(samples) {
  const sorted = [...samples].sort((left, right) => left - right);
  const middle = Math.floor(sorted.length / 2);
  return sorted.length % 2 === 0
    ? (sorted[middle - 1] + sorted[middle]) / 2
    : sorted[middle];
}

async function main() {
  // 1. Read the target URL from the first command-line argument.
  const url = process.argv[2];
  if (!url) throw new Error("usage: node stats.js <url-returning-json>");

  // 2. Make the HTTP GET request and parse the JSON body.
  const response = await fetch(url);
  // region:error_handling
  // Fail fast on a non-2xx status before we try to decode the body.
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} ${response.statusText}`);
  }
  // endregion:error_handling
  const document = await response.json();

  // 3. Gather every number from the decoded JSON.
  const numbers = collectNumbers(document);
  // region:error_handling
  if (numbers.length === 0) {
    throw new Error("the JSON response contained no numbers");
  }
  // endregion:error_handling

  // 4. Compute and print the statistics.
  console.log(`count:  ${numbers.length}`);
  console.log(`mean:   ${mean(numbers).toFixed(4)}`);
  console.log(`median: ${median(numbers).toFixed(4)}`);
}

main().catch((error) => {
  console.error(error.message);
  process.exitCode = 1;
});
"#;

pub(super) const PYTHON_PERSONAL_BUDGET_REPORT: &str = r#"from dataclasses import dataclass
from math import log
from pathlib import Path


@dataclass(frozen=True)
class CityCost:
    city: str
    average_rent: float
    living_cost_ex_rent: float
    source: str


CITY_COSTS = [
    CityCost('Moscow', 950.0, 850.0, 'https://www.numbeo.com/cost-of-living/in/Moscow'),
    CityCost('Berlin', 1550.0, 1250.0, 'https://www.numbeo.com/cost-of-living/in/Berlin'),
    CityCost('New York', 3600.0, 1850.0, 'https://www.numbeo.com/cost-of-living/in/New-York'),
]
ANNUAL_RETURN = 0.08
GOAL = 100_000.0


def budget_50_30_20(monthly_income):
    return {
        'needs': monthly_income * 0.50,
        'wants': monthly_income * 0.30,
        'savings': monthly_income * 0.20,
    }


def future_value(monthly_contribution, annual_return, years):
    monthly_rate = annual_return / 12
    months = years * 12
    return monthly_contribution * (((1 + monthly_rate) ** months - 1) / monthly_rate)


def years_to_goal(monthly_savings, goal=GOAL, annual_return=ANNUAL_RETURN):
    if monthly_savings <= 0:
        return None
    monthly_rate = annual_return / 12
    months = log(1 + goal * monthly_rate / monthly_savings) / log(1 + monthly_rate)
    return months / 12


def money(value):
    return f'${value:,.0f}'


def years(value):
    return 'not reachable' if value is None else f'{value:.1f}'


def comparison_rows(monthly_income):
    plan = budget_50_30_20(monthly_income)
    rows = []
    for cost in CITY_COSTS:
        expenses = cost.average_rent + cost.living_cost_ex_rent
        remaining = monthly_income - expenses
        monthly_savings = max(0.0, min(plan['savings'], remaining))
        rows.append({
            'city': cost.city,
            'rent': cost.average_rent,
            'remaining': remaining,
            'monthly_savings': monthly_savings,
            'years_to_100k': years_to_goal(monthly_savings),
            'source': cost.source,
        })
    return rows


def render_markdown(monthly_income):
    plan = budget_50_30_20(monthly_income)
    scenario_savings = 3000.0 * 0.20
    scenario_future = future_value(scenario_savings, ANNUAL_RETURN, 10)
    lines = [
        '# Budget Calculator Report',
        '',
        '## 50/30/20 Budget',
        f'- Monthly income: {money(monthly_income)}',
        f'- Needs (50%): {money(plan["needs"])}',
        f'- Wants (30%): {money(plan["wants"])}',
        f'- Savings (20%): {money(plan["savings"])}',
        '',
        '## Investment Scenario',
        f'- 20% of $3000 monthly: {money(scenario_savings)}',
        f'- Future value after 10 years at 8% annual return: {money(scenario_future)}',
        '',
        '## City Comparison',
        '| City | Average rent | Remaining budget after expenses | Years to save $100,000 |',
        '| --- | ---: | ---: | ---: |',
    ]
    for row in comparison_rows(monthly_income):
        lines.append(
            f'| {row["city"]} | {money(row["rent"])} | '
            f'{money(row["remaining"])} | {years(row["years_to_100k"])} |'
        )
    lines.extend(['', '## Sources'])
    for cost in CITY_COSTS:
        lines.append(f'- {cost.city}: {cost.source}')
    lines.append('')
    lines.append('Review and update the city-cost values after checking the source pages.')
    return '\n'.join(lines)


def read_income():
    try:
        raw = input('Monthly income in USD [3000]: ').strip()
    except EOFError:
        raw = ''
    return float(raw or '3000')


def main():
    report = render_markdown(read_income())
    Path('budget_report.md').write_text(report, encoding='utf-8')
    print(report)
    print('\nMarkdown report written to budget_report.md')


if __name__ == '__main__':
    main()
"#;

pub(super) const PYTHON_CRYPTO_PORTFOLIO_TRACKER: &str = r#"from dataclasses import dataclass
from typing import Mapping


@dataclass(frozen=True)
class AssetPrice:
    symbol: str
    price_usd: float
    change_24h_pct: float


PORTFOLIO = {
    'BTC': 2.5,
    'ETH': 15.0,
    'TON': 1000.0,
    'USDT': 5000.0,
}

MOCK_API_RESPONSE = {
    'BTC': {'price_usd': 64120.25, 'change_24h_pct': -2.4},
    'ETH': {'price_usd': 3350.80, 'change_24h_pct': 1.2},
    'TON': {'price_usd': 6.85, 'change_24h_pct': -5.7},
    'USDT': {'price_usd': 1.00, 'change_24h_pct': 0.0},
}


def fetch_prices(symbols: list[str]) -> dict[str, AssetPrice]:
    """Mock a public price API response for deterministic offline execution."""
    prices = {}
    for symbol in symbols:
        payload = MOCK_API_RESPONSE[symbol]
        prices[symbol] = AssetPrice(
            symbol=symbol,
            price_usd=payload['price_usd'],
            change_24h_pct=payload['change_24h_pct'],
        )
    return prices


def portfolio_rows(
    holdings: Mapping[str, float],
    prices: Mapping[str, AssetPrice],
) -> list[dict[str, float | str]]:
    total_value = sum(amount * prices[symbol].price_usd for symbol, amount in holdings.items())
    rows = []
    for symbol, amount in holdings.items():
        price = prices[symbol]
        value = amount * price.price_usd
        portfolio_weight = value / total_value * 100
        rows.append({
            'symbol': symbol,
            'amount': amount,
            'price_usd': price.price_usd,
            'value_usd': value,
            'change_24h_pct': price.change_24h_pct,
            'portfolio_weight': portfolio_weight,
        })
    return rows


def notify_alerts(rows: list[dict[str, float | str]]) -> list[str]:
    return [
        f'Notify: {row["symbol"]} dropped {row["change_24h_pct"]:.2f}% in 24h'
        for row in rows
        if float(row['change_24h_pct']) < -5.0
    ]


def money(value: float) -> str:
    return f'${value:,.2f}'


def render_dashboard(rows: list[dict[str, float | str]], notices: list[str]) -> str:
    total_value = sum(float(row['value_usd']) for row in rows)
    lines = [
        '# Crypto Portfolio Dashboard',
        '',
        f'**Total value:** {money(total_value)}',
        '',
        '| Asset | Amount | Price USD | Value USD | 24h change | Portfolio weight |',
        '| --- | ---: | ---: | ---: | ---: | ---: |',
    ]
    for row in rows:
        lines.append(
            f'| {row["symbol"]} | {row["amount"]:,.4g} | {money(float(row["price_usd"]))} | '
            f'{money(float(row["value_usd"]))} | {row["change_24h_pct"]:.2f}% | '
            f'{row["portfolio_weight"]:.2f}% |'
        )
    lines.extend(['', '## Alerts'])
    lines.extend(notices or ['No asset dropped more than 5% in the last 24h.'])
    return '\n'.join(lines)


def main() -> None:
    prices = fetch_prices(list(PORTFOLIO))
    rows = portfolio_rows(PORTFOLIO, prices)
    notices = notify_alerts(rows)
    formatted_log = render_dashboard(rows, notices)
    print(formatted_log)


if __name__ == '__main__':
    main()
"#;

pub(super) const PYTHON_SMART_TRAVEL_PLANNER: &str = r#"from dataclasses import dataclass


@dataclass(frozen=True)
class DestinationData:
    country: str
    visa_free: bool
    visa_note: str
    average_flight_cost: float
    daily_cost: float
    source: str


DEFAULT_DESTINATIONS = {
    'Japan': DestinationData(
        country='Japan',
        visa_free=False,
        visa_note='Russian citizens should confirm visa requirements before booking.',
        average_flight_cost=820.0,
        daily_cost=160.0,
        source='https://www.mofa.go.jp/',
    ),
    'UAE': DestinationData(
        country='UAE',
        visa_free=True,
        visa_note='Assume visa-free short-stay access; verify current entry rules.',
        average_flight_cost=420.0,
        daily_cost=135.0,
        source='https://u.ae/',
    ),
    'Serbia': DestinationData(
        country='Serbia',
        visa_free=True,
        visa_note='Assume visa-free short-stay access; verify current entry rules.',
        average_flight_cost=380.0,
        daily_cost=95.0,
        source='https://www.mfa.gov.rs/',
    ),
}
DEFAULT_DAYS = 7


def money(value):
    return f'${value:,.0f}'


class TravelPlanner:
    def __init__(self, destination_data=None):
        self.destination_data = destination_data or DEFAULT_DESTINATIONS
        self.destinations = []

    def add_destination(self, country: str, budget: float):
        lookup = {name.lower(): name for name in self.destination_data}
        key = country.strip().lower()
        if key not in lookup:
            available = ', '.join(sorted(self.destination_data))
            raise ValueError(f'Unknown destination {country!r}. Try one of: {available}')
        self.destinations.append({
            'country': lookup[key],
            'budget': float(budget),
        })

    def check_visa_requirements(self) -> bool:
        return all(
            self.destination_data[item['country']].visa_free
            for item in self._selected_destinations()
        )

    def estimate_total_cost(self) -> dict:
        return self._estimate_for_days(DEFAULT_DAYS)

    def generate_itinerary(self, days: int) -> str:
        estimates = self._estimate_for_days(days)
        ranked = sorted(
            estimates.values(),
            key=lambda row: (not row['visa_free'], row['estimated_total']),
        )
        lines = [
            '# Smart Travel Planner',
            '',
            f'Sample output for a {days}-day trip with $2,000 budget',
            '',
            '| Rank | Destination | Visa | Estimated cost | Budget status |',
            '| ---: | --- | --- | ---: | --- |',
        ]
        for rank, row in enumerate(ranked, start=1):
            visa = 'visa-free' if row['visa_free'] else 'visa check required'
            warning = row['budget_warning'] or 'Budget warning: none'
            lines.append(
                f'| {rank} | {row["country"]} | {visa} | '
                f'{money(row["estimated_total"])} | {warning} |'
            )
        lines.extend(['', '## Notes'])
        for row in ranked:
            lines.append(f'- {row["country"]}: {row["visa_note"]}')
            lines.append(f'  Source to review: {row["source"]}')
        lines.append('')
        lines.append('Review live visa rules and flight prices before purchase.')
        return '\n'.join(lines)

    def _selected_destinations(self):
        if not self.destinations:
            raise ValueError('Add at least one destination first.')
        return self.destinations

    def _estimate_for_days(self, days):
        estimates = {}
        for item in self._selected_destinations():
            data = self.destination_data[item['country']]
            total = data.average_flight_cost + data.daily_cost * days
            budget = item['budget']
            estimates[data.country] = {
                'country': data.country,
                'visa_free': data.visa_free,
                'visa_note': data.visa_note,
                'source': data.source,
                'average_flight_cost': data.average_flight_cost,
                'daily_cost': data.daily_cost,
                'estimated_total': total,
                'budget': budget,
                'budget_warning': (
                    None
                    if budget >= total
                    else f'Budget warning: {money(budget)} is below {money(total)}'
                ),
            }
        return estimates


def build_sample_planner():
    planner = TravelPlanner()
    for country in ('Japan', 'UAE', 'Serbia'):
        planner.add_destination(country, 2000.0)
    return planner


if __name__ == '__main__':
    sample = build_sample_planner()
    print('Sample output for a 7-day trip with $2,000 budget')
    print(sample.generate_itinerary(7))
"#;

pub(super) const RUST_SELF_SOURCE_METRICS: &str = r#"use std::fmt::Write as _;

const SOURCE: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", file!()));
const RESPONSE_REASONING: &str = "The response decomposes the request, provides a source-metrics program, and compares the code with this prose.";

#[derive(Default)]
struct Metrics {
    functions: usize,
    loops: usize,
    conditionals: usize,
    comments: usize,
    boolean_branches: usize,
    complexity_score: usize,
}

fn main() {
    let source_metrics = analyze_rust_text(SOURCE);
    let reasoning_metrics = analyze_rust_text(RESPONSE_REASONING);
    println!("{}", render_report(&source_metrics, &reasoning_metrics));
}

fn analyze_rust_text(text: &str) -> Metrics {
    let (sanitized, comments) = sanitize_rust_text(text);
    let tokens = rust_tokens(&sanitized);
    let loops = count_any(&tokens, &["for", "while", "loop"]);
    let conditionals = count_any(&tokens, &["if", "match"]);
    let boolean_branches = sanitized.matches("&&").count() + sanitized.matches("||").count();
    Metrics {
        functions: count_any(&tokens, &["fn"]),
        loops,
        conditionals,
        comments,
        boolean_branches,
        complexity_score: 1 + loops + conditionals + boolean_branches,
    }
}

fn sanitize_rust_text(text: &str) -> (String, usize) {
    let mut output = String::with_capacity(text.len());
    let chars: Vec<char> = text.chars().collect();
    let mut comments = 0;
    let mut index = 0;
    while index < chars.len() {
        match (chars[index], chars.get(index + 1)) {
            ('/', Some('/')) => {
                comments += 1;
                output.push(' ');
                output.push(' ');
                index += 2;
                while index < chars.len() && chars[index] != '\n' {
                    output.push(' ');
                    index += 1;
                }
            }
            ('/', Some('*')) => {
                comments += 1;
                output.push(' ');
                output.push(' ');
                index += 2;
                while index + 1 < chars.len() && !(chars[index] == '*' && chars[index + 1] == '/') {
                    output.push(if chars[index] == '\n' { '\n' } else { ' ' });
                    index += 1;
                }
                if index + 1 < chars.len() {
                    output.push(' ');
                    output.push(' ');
                    index += 2;
                }
            }
            ('"', _) => {
                output.push(' ');
                index += 1;
                while index < chars.len() {
                    let current = chars[index];
                    output.push(if current == '\n' { '\n' } else { ' ' });
                    index += if current == '\\' && index + 1 < chars.len() { 2 } else { 1 };
                    if current == '"' {
                        break;
                    }
                }
            }
            _ => {
                output.push(chars[index]);
                index += 1;
            }
        }
    }
    (output, comments)
}

fn rust_tokens(text: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    for character in text.chars() {
        if character == '_' || character.is_ascii_alphanumeric() {
            current.push(character);
        } else if !current.is_empty() {
            tokens.push(std::mem::take(&mut current));
        }
    }
    if !current.is_empty() {
        tokens.push(current);
    }
    tokens
}

fn count_any(tokens: &[String], needles: &[&str]) -> usize {
    tokens
        .iter()
        .filter(|token| needles.iter().any(|needle| token.as_str() == *needle))
        .count()
}

fn render_report(source: &Metrics, reasoning: &Metrics) -> String {
    let verdict = if source.complexity_score > reasoning.complexity_score {
        "generated_code"
    } else if source.complexity_score < reasoning.complexity_score {
        "reasoning_text"
    } else {
        "tie"
    };
    let explanation = if verdict == "generated_code" {
        "The generated Rust code is more complex because it contains functions, loops, conditionals, and comment syntax; the reasoning text is plain prose."
    } else if verdict == "reasoning_text" {
        "The reasoning text is more complex under this scanner."
    } else {
        "Both texts have the same computed complexity score."
    };
    let mut report = String::new();
    report.push_str("{\n");
    push_metrics(&mut report, "source_code", source, true);
    push_metrics(&mut report, "response_reasoning_text", reasoning, true);
    writeln!(report, "  \"more_complex\": \"{}\",", verdict).unwrap();
    writeln!(report, "  \"comparison\": {}", json_string(explanation)).unwrap();
    report.push('}');
    report
}

fn push_metrics(report: &mut String, label: &str, metrics: &Metrics, comma: bool) {
    writeln!(report, "  \"{}\": {{", label).unwrap();
    writeln!(report, "    \"functions\": {},", metrics.functions).unwrap();
    writeln!(report, "    \"loops\": {},", metrics.loops).unwrap();
    writeln!(report, "    \"conditionals\": {},", metrics.conditionals).unwrap();
    writeln!(report, "    \"comments\": {},", metrics.comments).unwrap();
    writeln!(report, "    \"boolean_branches\": {},", metrics.boolean_branches).unwrap();
    writeln!(report, "    \"complexity_score\": {}", metrics.complexity_score).unwrap();
    writeln!(report, "  }}{}", if comma { "," } else { "" }).unwrap();
}

fn json_string(value: &str) -> String {
    let mut escaped = String::new();
    for character in value.chars() {
        match character {
            '"' => escaped.push_str("\\\""),
            '\\' => escaped.push_str("\\\\"),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            other => escaped.push(other),
        }
    }
    format!("\"{}\"", escaped)
}
"#;