package core

import "core:fmt"

script_is_valid_minimal :: proc(script: Comic_Script) -> bool {
	if len(script.title) == 0 {
		return false
	}
	if len(script.synopsis) == 0 {
		return false
	}
	if len(script.pages) == 0 {
		return false
	}
	return true
}

normalize_script :: proc(script: Comic_Script) -> Comic_Script {
	normalized := script

	if len(normalized.title) == 0 {
		normalized.title = fmt.aprintf("Untitled Comic")
	}
	if len(normalized.synopsis) == 0 {
		normalized.synopsis = fmt.aprintf("Generated comic synopsis")
	}

	for idx in 0..<len(normalized.characters) {
		if len(normalized.characters[idx].id) == 0 {
			normalized.characters[idx].id = fmt.aprintf("char_%03d", idx+1)
		}
		if len(normalized.characters[idx].name) == 0 {
			normalized.characters[idx].name = fmt.aprintf("Character %d", idx+1)
		}
		if normalized.characters[idx].seed == 0 {
			normalized.characters[idx].seed = derive_seed_from_string(normalized.characters[idx].name)
		}
	}

	for page_idx in 0..<len(normalized.pages) {
		if normalized.pages[page_idx].page_number <= 0 {
			normalized.pages[page_idx].page_number = page_idx + 1
		}

		for panel_idx in 0..<len(normalized.pages[page_idx].panels) {
			if len(normalized.pages[page_idx].panels[panel_idx].panel_id) == 0 {
				normalized.pages[page_idx].panels[panel_idx].panel_id = fmt.aprintf("panel_%03d_%03d", page_idx+1, panel_idx+1)
			}
			if normalized.pages[page_idx].panels[panel_idx].panel_number <= 0 {
				normalized.pages[page_idx].panels[panel_idx].panel_number = panel_idx + 1
			}
		}
	}

	return normalized
}

count_character_appearances :: proc(script: ^Comic_Script) {
	for i in 0..<len(script.characters) {
		char_id := script.characters[i].id
		count := 0
		first_panel := ""
		for page_idx in 0..<len(script.pages) {
			for panel_idx in 0..<len(script.pages[page_idx].panels) {
				panel := &script.pages[page_idx].panels[panel_idx]
				for cid in panel.characters_present {
					if cid == char_id {
						count += 1
						if len(first_panel) == 0 {
							first_panel = panel.panel_id
						}
						break
					}
				}
			}
		}
		script.characters[i].appearance_count = count
		script.characters[i].first_appearance_panel = first_panel
	}
}
