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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/*!
 * A timetable vocabulary.
 *
 * Copyright (C) 2023-2024 kaoru  <https://www.tetengo.org/>
 */

use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::{BufRead, Lines};
use std::rc::Rc;

use anyhow::Result;

use tetengo_lattice::{Entry, EntryView, HashMapVocabulary, StringInput, Vocabulary};

/**
 * A timetable error.
 */
#[derive(Clone, Copy, Debug, thiserror::Error)]
pub(crate) enum TimetableError {
    /**
     * Unexpected end of file.
     */
    #[error("unexpected end of file")]
    UnexpectedEndOfFile,

    /**
     * Station names and telegram codes unmatch.
     */
    #[error("station names and telegram codes unmatch")]
    StationNamesAndTelegramCodesUnmatch,

    /**
     * Invalid train line found.
     */
    #[error("invalid train line found")]
    InvalidTrainLineFound,

    /**
     * Invalid arrival/departure time found.
     */
    #[error("invalid arrival/departure time found")]
    InvalidArrivalOrDepartureTimeFound,

    /**
     * Invalid time found.
     */
    #[error("invalid time found")]
    InvalidTimeFound,

    /**
     * Both arrival and departure time not found.
     */
    #[error("both arrival and departure time not found")]
    BothArrivalAndDepartureTimeNotFound,
}

/**
 * A station.
 */
#[derive(Debug)]
pub(crate) struct Station {
    name: String,
    telegram_code: String,
}

impl Station {
    /**
     * Creates a station.
     *
     * # Arguments
     * * `name`          - A name.
     * * `telegram_code` - A telegram code.
     */
    pub(crate) const fn new(name: String, telegram_code: String) -> Self {
        Self {
            name,
            telegram_code,
        }
    }

    /**
     * Returns the name.
     *
     * # Returns
     * The name.
     */
    pub(crate) fn name(&self) -> &str {
        self.name.as_str()
    }

    /**
     * Returns the telegram code.
     *
     * # Returns
     * The telegram code.
     */
    pub(crate) fn telegram_code(&self) -> &str {
        self.telegram_code.as_str()
    }
}

/**
 * A stop.
 */
#[derive(Clone, Debug)]
pub(crate) struct Stop {
    arrival_time: Option<usize>,
    departure_time: Option<usize>,
}

impl Stop {
    /**
     * Creates a stop.
     *
     * # Arguments
     * * `arrival_time`   - An arrival time.
     * * `departure_time` - A departure time.
     */
    pub(crate) const fn new(arrival_time: Option<usize>, departure_time: Option<usize>) -> Self {
        Self {
            arrival_time,
            departure_time,
        }
    }

    /**
     * Returns the arrival time.
     *
     * # Returns
     * The arrival time.
     */
    pub(crate) const fn arrival_time(&self) -> Option<usize> {
        self.arrival_time
    }

    /**
     * Sets an arrival time.
     *
     * # Arguments
     * * `time` - An arrival time.
     */
    pub(crate) fn set_arrival_time(&mut self, time: usize) {
        self.arrival_time = Some(time);
    }

    /**
     * Returns the departure time.
     *
     * # Returns
     * The departure time.
     */
    pub(crate) const fn departure_time(&self) -> Option<usize> {
        self.departure_time
    }

    /**
     * Sets a departure time.
     *
     * # Arguments
     * * `time` - A departure time.
     */
    pub(crate) fn set_departure_time(&mut self, time: usize) {
        self.departure_time = Some(time);
    }
}

/**
 * A train.
 */
#[derive(Clone, Debug)]
pub(crate) struct Train {
    number: String,
    name: String,
    stops: Vec<Stop>,
}

impl Train {
    /**
     * Creates a train.
     *
     * # Arguments
     * * `number` - A number.
     * * `name`   - A name.
     * * `stops`  - Stops.
     */
    pub(crate) const fn new(number: String, name: String, stops: Vec<Stop>) -> Self {
        Self {
            number,
            name,
            stops,
        }
    }

    /**
     * Returns the number.
     *
     * # Returns
     * The number.
     */
    pub(crate) fn number(&self) -> &str {
        self.number.as_str()
    }

    /**
     * Returns the name.
     *
     * # Returns
     * The name.
     */
    pub(crate) fn name(&self) -> &str {
        self.name.as_str()
    }

    /**
     * Returns the stops.
     *
     * # Returns
     * The stops.
     */
    pub(crate) fn stops(&self) -> &[Stop] {
        self.stops.as_slice()
    }

    /**
     * Returns the stops.
     *
     * # Returns
     * The stops.
     */
    pub(crate) fn stops_mut(&mut self) -> &mut Vec<Stop> {
        &mut self.stops
    }
}

/**
 * A section.
 */
#[derive(Clone, Debug)]
pub(crate) struct Section {
    train: Rc<Train>,
    from: usize,
    to: usize,
}

impl Section {
    /**
     * Creates a section.
     *
     * # Arguments
     * * `train` - A train.
     * * `from`  - A departure station index.
     * * `to`    - An arrival station index.
     */
    pub(crate) const fn new(train: Rc<Train>, from: usize, to: usize) -> Self {
        Self { train, from, to }
    }

    /**
     * Returns the train.
     *
     * # Returns
     * The train.
     */
    pub(crate) fn train(&self) -> &Train {
        self.train.as_ref()
    }

    /**
     * Returns the departure station index.
     *
     * # Returns
     * The departure station index.
     */
    pub(crate) const fn from(&self) -> usize {
        self.from
    }

    /**
     * Returns the arrival station index.
     *
     * # Returns
     * The arrival station index.
     */
    pub(crate) const fn to(&self) -> usize {
        self.to
    }
}

#[derive(Debug)]
struct TimetableValue {
    stations: Vec<Station>,
    trains: Vec<Train>,
}

impl TimetableValue {
    const fn new(stations: Vec<Station>, trains: Vec<Train>) -> Self {
        Self { stations, trains }
    }
}

/**
 * A timetable vocabulary.
 */
#[derive(Debug)]
pub(crate) struct Timetable {
    value: TimetableValue,
}

impl Timetable {
    /**
     * Creates a timetable vocabulary.
     *
     * # Arguments
     * * `reader` - A reader.
     */
    pub(crate) fn new(reader: Box<dyn BufRead>) -> Result<Self> {
        Ok(Self {
            value: Self::build_timetable(reader)?,
        })
    }

    fn build_timetable(mut reader: Box<dyn BufRead>) -> Result<TimetableValue> {
        let mut value = Self::parse_input(reader.as_mut())?;
        Self::guess_arrival_times(&mut value)?;
        Ok(value)
    }

    fn parse_input(reader: &mut dyn BufRead) -> Result<TimetableValue> {
        let mut lines = reader.lines();

        let stations = {
            let Some(line1) = Self::read_line(&mut lines)? else {
                return Err(TimetableError::UnexpectedEndOfFile.into());
            };
            let Some(line2) = Self::read_line(&mut lines)? else {
                return Err(TimetableError::UnexpectedEndOfFile.into());
            };
            Self::parse_stations(line1, line2)?
        };

        let trains = {
            let mut trains = Vec::new();
            while let Some(line) = Self::read_line(&mut lines)? {
                if line.is_empty() || (line.len() == 1 && line[0].is_empty()) {
                    continue;
                }
                trains.push(Self::parse_train(line, stations.len())?);
            }
            trains
        };

        Ok(TimetableValue::new(stations, trains))
    }

    fn read_line(lines: &mut Lines<&mut dyn BufRead>) -> Result<Option<Vec<String>>> {
        let Some(line) = lines.next() else {
            return Ok(None);
        };
        let line = line?;
        let elements = line
            .split(',')
            .map(|e| e.trim().to_string())
            .collect::<Vec<_>>();
        Ok(Some(elements))
    }

    fn parse_stations(line1: Vec<String>, line2: Vec<String>) -> Result<Vec<Station>> {
        if line1.len() != line2.len() {
            return Err(TimetableError::StationNamesAndTelegramCodesUnmatch.into());
        }
        let stations = line1
            .into_iter()
            .skip(2)
            .zip(line2.into_iter().skip(2))
            .map(|(name, telegram_code)| Station::new(name, telegram_code))
            .collect::<Vec<_>>();
        Ok(stations)
    }

    fn parse_train(mut line: Vec<String>, station_count: usize) -> Result<Train> {
        if line.len() > station_count + 2 {
            return Err(TimetableError::InvalidTrainLineFound.into());
        }
        line.resize(station_count + 2, String::new());
        let number = line[0].clone();
        let name = line[1].clone();
        let stops = line
            .into_iter()
            .skip(2)
            .map(Self::to_stop)
            .collect::<Result<Vec<_>>>()?;
        Ok(Train::new(number, name, stops))
    }

    fn to_stop(element: String) -> Result<Stop> {
        let string_times = element
            .split('/')
            .map(|e| e.trim().to_string())
            .collect::<Vec<_>>();
        if string_times.is_empty() || string_times.len() > 2 {
            Err(TimetableError::InvalidArrivalOrDepartureTimeFound.into())
        } else if string_times.len() == 1 {
            Ok(Stop::new(None, Self::to_minutes(string_times[0].as_str())?))
        } else {
            Ok(Stop::new(
                Self::to_minutes(string_times[0].as_str())?,
                Self::to_minutes(string_times[1].as_str())?,
            ))
        }
    }

    fn to_minutes(string_time: &str) -> Result<Option<usize>> {
        if string_time.is_empty() || string_time == "-" {
            return Ok(None);
        }
        let int_time = string_time.parse::<usize>()?;
        let hour = int_time / 100;
        let minute = int_time - hour * 100;
        if hour >= 24 || minute >= 60 {
            return Err(TimetableError::InvalidTimeFound.into());
        }
        Ok(Some(hour * 60 + minute))
    }

    fn guess_arrival_times(value: &mut TimetableValue) -> Result<()> {
        for from in 0..value.stations.len() - 1 {
            for to in from + 1..value.stations.len() {
                let minimum_duration = Self::minimum_duration(value.trains.as_ref(), from, to)?;
                for train in &mut value.trains {
                    if !Self::all_passing(train.stops(), from, to) {
                        continue;
                    }
                    if train.stops()[to].arrival_time().is_none() {
                        let Some(from_departure_time) = train.stops()[from].departure_time() else {
                            return Err(TimetableError::BothArrivalAndDepartureTimeNotFound.into());
                        };
                        train.stops_mut()[to].set_arrival_time(Self::add_time(
                            from_departure_time,
                            minimum_duration,
                        ));
                    } else if train.stops()[from].departure_time().is_none() {
                        let Some(to_arrival_time) = train.stops()[to].arrival_time() else {
                            return Err(TimetableError::BothArrivalAndDepartureTimeNotFound.into());
                        };
                        train.stops_mut()[from]
                            .set_departure_time(Self::add_time(to_arrival_time, -minimum_duration));
                    }
                }
            }
        }
        Ok(())
    }

    fn minimum_duration(trains: &[Train], from: usize, to: usize) -> Result<isize> {
        let mut minimum = isize::MAX;
        for train in trains {
            if !Self::all_passing(train.stops(), from, to) {
                continue;
            }
            let from_time = if let Some(departure_time) = train.stops()[from].departure_time() {
                departure_time
            } else if let Some(arrival_time) = train.stops()[from].arrival_time() {
                arrival_time
            } else {
                return Err(TimetableError::BothArrivalAndDepartureTimeNotFound.into());
            };
            let to_time = if let Some(arrival_time) = train.stops()[to].arrival_time() {
                arrival_time
            } else if let Some(departure_time) = train.stops()[to].departure_time() {
                departure_time
            } else {
                return Err(TimetableError::BothArrivalAndDepartureTimeNotFound.into());
            };
            let duration = Self::diff_time(to_time, from_time);
            if duration < minimum {
                minimum = duration;
            }
        }
        Ok(minimum)
    }

    /**
     * Returns the stations.
     *
     * # Returns
     * The stations.
     */
    pub(crate) fn stations(&self) -> &[Station] {
        self.value.stations.as_slice()
    }

    /**
     * Returns the station index.
     *
     * # Arguments
     * * `name_or_telegram_code` - A name or telegram code.
     *
     * # Returns
     * The index. Or `stations().len()` if no station is found.
     */
    pub(crate) fn station_index(&self, name_or_telegram_code: &str) -> usize {
        for (i, station) in self.value.stations.iter().enumerate() {
            if station.name().to_lowercase() == name_or_telegram_code.to_lowercase()
                || station.telegram_code().to_uppercase() == name_or_telegram_code.to_uppercase()
            {
                return i;
            }
        }
        self.value.stations.len()
    }

    /**
     * Creates a vocabulary.
     *
     * # Arguments
     * * `departure_time` - A departure time.
     *
     * # Returns
     * A vocabulary.
     */
    pub(crate) fn create_vocabulary(&self, departure_time: usize) -> Box<dyn Vocabulary> {
        let entries = Self::build_entries(&self.value);
        let connections = Self::build_connections(&entries, departure_time);
        Box::new(HashMapVocabulary::new(
            entries,
            connections,
            &Self::entry_hash_value,
            &Self::entry_equal_to,
        ))
    }

    fn build_entries(timetable: &TimetableValue) -> Vec<(String, Vec<Entry>)> {
        let mut map = HashMap::<String, Vec<Entry>>::new();
        for train in &timetable.trains {
            for from in 0..timetable.stations.len() - 1 {
                for to in from + 1..timetable.stations.len() {
                    if !Self::all_passing(train.stops(), from, to) {
                        continue;
                    }

                    let section_name = Self::make_section_name(&timetable.stations, from, to);
                    let found = map.entry(section_name.clone()).or_default();
                    let section = Section::new(Rc::new(train.clone()), from, to);
                    found.push(Entry::new(
                        Box::new(StringInput::new(section_name)),
                        Box::new(section),
                        Self::make_section_duration(train.stops(), from, to) as i32,
                    ));
                }
            }
        }
        map.into_iter().collect::<Vec<_>>()
    }

    fn all_passing(stops: &[Stop], from: usize, to: usize) -> bool {
        if stops[from].arrival_time().is_none() && stops[from].departure_time().is_none() {
            return false;
        }
        if stops[to].arrival_time().is_none() && stops[to].departure_time().is_none() {
            return false;
        }
        for stop in stops.iter().take(to).skip(from + 1) {
            if stop.arrival_time().is_some() || stop.departure_time().is_some() {
                return false;
            }
        }
        true
    }

    fn make_section_name(stations: &[Station], from: usize, to: usize) -> String {
        let mut name = String::new();
        for i in from..to {
            name += &format!(
                "{}-{}/",
                stations[i].telegram_code(),
                stations[i + 1].telegram_code()
            );
        }
        name
    }

    fn make_section_duration(stops: &[Stop], from: usize, to: usize) -> usize {
        let departure_time = stops[from].departure_time().unwrap_or_else(|| {
            unreachable!("departure_time must be set.");
        });
        let arrival_time = stops[to].arrival_time().unwrap_or_else(|| {
            unreachable!("arrival_time must be set.");
        });
        Self::diff_time(arrival_time, departure_time) as usize
    }

    fn build_connections(
        entries: &[(String, Vec<Entry>)],
        departure_time: usize,
    ) -> Vec<((Entry, Entry), i32)> {
        let mut connections = Vec::<((Entry, Entry), i32)>::new();

        for (_, from_entries) in entries {
            for (_, to_entries) in entries {
                for from_entry in from_entries {
                    for to_entry in to_entries {
                        let from_value = from_entry
                            .value()
                            .unwrap_or_else(|| {
                                unreachable!("from_entry.value() must not be empty.")
                            })
                            .as_any()
                            .downcast_ref::<Section>()
                            .unwrap_or_else(|| unreachable!("from_entry.value() must be Section."));
                        let to_value = to_entry
                            .value()
                            .unwrap_or_else(|| unreachable!("to_entry.value() must not be empty."))
                            .as_any()
                            .downcast_ref::<Section>()
                            .unwrap_or_else(|| unreachable!("to_entry.value() must be Section."));
                        if from_value.to() != to_value.from() {
                            continue;
                        }

                        let from_arrival_time = from_value.train().stops()[from_value.to()]
                            .arrival_time()
                            .unwrap_or_else(|| {
                                unreachable!("from arrival_time must be set.");
                            });
                        let to_departure_time = to_value.train().stops()[to_value.from()]
                            .departure_time()
                            .unwrap_or_else(|| {
                                unreachable!("to departure_time must be set.");
                            });
                        let cost = Self::diff_time(to_departure_time, from_arrival_time) as i32;
                        if cost > 60 {
                            continue;
                        }
                        if from_value.train().number() != to_value.train().number() {
                            connections.push(((from_entry.clone(), to_entry.clone()), cost + 1));
                        } else {
                            connections.push(((from_entry.clone(), to_entry.clone()), cost));
                        }
                    }
                }
            }
        }

        for (_, entries) in entries {
            for entry in entries {
                let section = entry
                    .value()
                    .unwrap_or_else(|| unreachable!("entry.value() must not be empty."))
                    .as_any()
                    .downcast_ref::<Section>()
                    .unwrap_or_else(|| unreachable!("entry.value() must be Section."));
                let section_departure_time = section.train().stops()[section.from()]
                    .departure_time()
                    .unwrap_or_else(|| {
                        unreachable!("departure_time() must be set.");
                    });
                let bos_cost = Self::diff_time(section_departure_time, departure_time) as i32;
                if bos_cost <= 240 {
                    connections.push(((Entry::BosEos, entry.clone()), bos_cost * 9 / 10));
                }
                connections.push(((entry.clone(), Entry::BosEos), 0));
            }
        }

        connections
    }

    const fn add_time(time: usize, duration: isize) -> usize {
        assert!(time < 1440);
        assert!(-1440 < duration && duration < 1440);
        (time as isize + 1440 + duration) as usize % 1440
    }

    const fn diff_time(time1: usize, time2: usize) -> isize {
        assert!(time1 < 1440);
        assert!(time2 < 1440);
        (time1 as isize + 1440 - time2 as isize) % 1440
    }

    fn entry_hash_value(entry: &EntryView<'_>) -> u64 {
        let mut hasher = DefaultHasher::new();

        hasher.write_u64(if let Some(key) = entry.key() {
            key.hash_value()
        } else {
            0
        });
        let section = if let Some(value) = entry.value() {
            value.as_any().downcast_ref::<Section>()
        } else {
            None
        };
        if let Some(section) = section {
            section.train().number().hash(&mut hasher);
            section.train().name().hash(&mut hasher);
            section.from().hash(&mut hasher);
            section.to().hash(&mut hasher);
        } else {
            "".hash(&mut hasher);
            "".hash(&mut hasher);
            0usize.hash(&mut hasher);
            0usize.hash(&mut hasher);
        }
        hasher.finish()
    }

    fn entry_equal_to(one: &EntryView<'_>, another: &EntryView<'_>) -> bool {
        if let Some(one_value) = one.value() {
            if let Some(another_value) = another.value() {
                let Some(one_section) = one_value.as_any().downcast_ref::<Section>() else {
                    unreachable!("one.value() must be Section.");
                };
                let Some(another_section) = another_value.as_any().downcast_ref::<Section>() else {
                    unreachable!("another.value() must be Section.");
                };
                let is_equal = if let Some(one_key) = one.key() {
                    if let Some(another_key) = another.key() {
                        one_key.equal_to(another_key)
                    } else {
                        false
                    }
                } else {
                    another.key().is_none()
                } && one_section.train().number()
                    == another_section.train().number()
                    && one_section.train().name() == another_section.train().name()
                    && one_section.from() == another_section.from()
                    && one_section.to() == another_section.to();
                is_equal
            } else {
                false
            }
        } else if another.value().is_none() {
            let is_equal = if let Some(one_key) = one.key() {
                if let Some(another_key) = another.key() {
                    one_key.equal_to(another_key)
                } else {
                    false
                }
            } else {
                another.key().is_none()
            };
            is_equal
        } else {
            false
        }
    }
}