use super::*;
use crate::test_support::unique_temp_path;

#[test]
fn loads_overlay_import_document_with_relative_paths() {
    let fixture_dir = unique_temp_path("overlay-import", "dir");
    std::fs::create_dir_all(&fixture_dir).expect("fixture dir should be created");

    let snapshot_path = fixture_dir.join("base.json");
    let save_slice_path = fixture_dir.join("slice.json");
    let overlay_path = fixture_dir.join("overlay.json");

    let snapshot = RuntimeSnapshotDocument {
        format_version: SNAPSHOT_FORMAT_VERSION,
        snapshot_id: "base".to_string(),
        source: RuntimeSnapshotSource {
            source_fixture_id: None,
            description: Some("base snapshot".to_string()),
        },
        state: RuntimeState {
            calendar: CalendarPoint {
                year: 1835,
                month_slot: 1,
                phase_slot: 2,
                tick_slot: 4,
            },
            world_flags: BTreeMap::new(),
            save_profile: RuntimeSaveProfileState::default(),
            world_restore: RuntimeWorldRestoreState::default(),
            metadata: BTreeMap::new(),
            companies: vec![crate::state::RuntimeCompany {
                company_id: 42,
                controller_kind: RuntimeCompanyControllerKind::Human,
                current_cash: 100,
                debt: 0,
                credit_rating_score: None,
                prime_rate: None,
                track_piece_counts: RuntimeTrackPieceCounts::default(),
                active: true,
                available_track_laying_capacity: None,
                linked_chairman_profile_id: None,
                book_value_per_share: 0,
                investor_confidence: 0,
                management_attitude: 0,
                takeover_cooldown_year: None,
                merger_cooldown_year: None,
            }],
            selected_company_id: Some(42),
            players: Vec::new(),
            selected_player_id: None,
            chairman_profiles: Vec::new(),
            selected_chairman_profile_id: None,
            trains: Vec::new(),
            locomotive_catalog: Vec::new(),
            cargo_catalog: Vec::new(),
            territories: Vec::new(),
            company_territory_track_piece_counts: Vec::new(),
            company_territory_access: Vec::new(),
            packed_event_collection: None,
            event_runtime_records: Vec::new(),
            candidate_availability: BTreeMap::new(),
            named_locomotive_availability: BTreeMap::new(),
            named_locomotive_cost: BTreeMap::new(),
            all_cargo_price_override: None,
            named_cargo_price_overrides: BTreeMap::new(),
            all_cargo_production_override: None,
            factory_cargo_production_override: None,
            farm_mine_cargo_production_override: None,
            named_cargo_production_overrides: BTreeMap::new(),
            cargo_production_overrides: BTreeMap::new(),
            world_runtime_variables: BTreeMap::new(),
            company_runtime_variables: BTreeMap::new(),
            player_runtime_variables: BTreeMap::new(),
            territory_runtime_variables: BTreeMap::new(),
            world_scalar_overrides: BTreeMap::new(),
            special_conditions: BTreeMap::new(),
            service_state: RuntimeServiceState::default(),
        },
    };
    save_runtime_snapshot_document(&snapshot_path, &snapshot).expect("snapshot should save");

    let save_slice_document = RuntimeSaveSliceDocument {
        format_version: SAVE_SLICE_DOCUMENT_FORMAT_VERSION,
        save_slice_id: "slice".to_string(),
        source: RuntimeSaveSliceDocumentSource::default(),
        save_slice: SmpLoadedSaveSlice {
            file_extension_hint: Some("gms".to_string()),
            container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
            mechanism_family: "classic-save-rehydrate-v1".to_string(),
            mechanism_confidence: "grounded".to_string(),
            trailer_family: None,
            bridge_family: None,
            profile: None,
            candidate_availability_table: None,
            named_locomotive_availability_table: None,
            locomotive_catalog: None,
            cargo_catalog: None,
            world_issue_37_state: None,
            world_economic_tuning_state: None,
            world_finance_neighborhood_state: None,
            world_locomotive_policy_state: None,
            company_roster: None,
            chairman_profile_table: None,
            region_collection: None,
            region_fixed_row_run_summary: None,
            placed_structure_collection: None,
            placed_structure_dynamic_side_buffer_summary: None,
            special_conditions_table: None,
            event_runtime_collection: Some(SmpLoadedEventRuntimeCollectionSummary {
                source_kind: "packed-event-runtime-collection".to_string(),
                mechanism_family: "classic-save-rehydrate-v1".to_string(),
                mechanism_confidence: "grounded".to_string(),
                container_profile_family: Some("rt3-classic-save-container-v1".to_string()),
                metadata_tag_offset: 0x7100,
                records_tag_offset: 0x7200,
                close_tag_offset: 0x7600,
                packed_state_version: 0x3e9,
                packed_state_version_hex: "0x000003e9".to_string(),
                live_id_bound: 7,
                live_record_count: 1,
                live_entry_ids: vec![7],
                decoded_record_count: 1,
                imported_runtime_record_count: 0,
                records_with_trigger_kind: 0,
                records_missing_trigger_kind: 0,
                nondirect_compact_record_count: 0,
                nondirect_compact_records_missing_trigger_kind: 0,
                trigger_kinds_present: vec![],
                control_lane_notes: vec![],
                add_building_dispatch_strip_record_indexes: vec![],
                add_building_dispatch_strip_descriptor_labels: vec![],
                add_building_dispatch_strip_records_with_trigger_kind: 0,
                add_building_dispatch_strip_records_missing_trigger_kind: 0,
                add_building_dispatch_strip_row_shape_families: vec![],
                add_building_dispatch_strip_signature_families: vec![],
                add_building_dispatch_strip_condition_tuple_families: vec![],
                add_building_dispatch_strip_signature_condition_clusters: vec![],
                records: vec![SmpLoadedPackedEventRecordSummary {
                    record_index: 0,
                    live_entry_id: 7,
                    payload_offset: Some(0x7202),
                    payload_len: Some(48),
                    decode_status: "parity_only".to_string(),
                    payload_family: "synthetic_harness".to_string(),
                    trigger_kind: Some(7),
                    active: Some(true),
                    marks_collection_dirty: Some(false),
                    one_shot: Some(false),
                    compact_control: None,
                    text_bands: packed_text_bands(),
                    standalone_condition_row_count: 0,
                    standalone_condition_rows: vec![],
                    negative_sentinel_scope: None,
                    grouped_effect_row_counts: vec![0, 0, 0, 0],
                    grouped_effect_rows: vec![],
                    decoded_conditions: Vec::new(),
                    decoded_actions: vec![RuntimeEffect::AdjustCompanyCash {
                        target: crate::event::targets::RuntimeCompanyTarget::Ids { ids: vec![42] },
                        delta: 50,
                    }],
                    executable_import_ready: false,
                    notes: vec!["needs company context".to_string()],
                }],
            }),
            notes: vec![],
        },
    };
    save_runtime_save_slice_document(&save_slice_path, &save_slice_document)
        .expect("save slice should save");

    let overlay = RuntimeOverlayImportDocument {
        format_version: OVERLAY_IMPORT_DOCUMENT_FORMAT_VERSION,
        import_id: "overlay-relative".to_string(),
        source: RuntimeOverlayImportDocumentSource {
            description: Some("relative overlay".to_string()),
            notes: vec![],
        },
        base_snapshot_path: "base.json".to_string(),
        save_slice_path: "slice.json".to_string(),
    };
    save_runtime_overlay_import_document(&overlay_path, &overlay)
        .expect("overlay document should save");

    let input =
        load_runtime_state_input(&overlay_path).expect("overlay runtime import should load");
    assert_eq!(input.input_id, "overlay-relative");
    assert_eq!(input.state.event_runtime_records.len(), 1);
    assert_eq!(input.state.companies[0].company_id, 42);

    let _ = std::fs::remove_file(snapshot_path);
    let _ = std::fs::remove_file(save_slice_path);
    let _ = std::fs::remove_file(overlay_path);
    let _ = std::fs::remove_dir(fixture_dir);
}
