import json
import os
import sys
import random

def create_tiddler(title, content, tags=None):
    tiddler = f"title: {title}\n"
    if tags:
        tiddler += f"tags: {' '.join(tags)}\n"
    tiddler += "\n"
    tiddler += content
    return tiddler

def parse_population(pop_string):
    return int(pop_string.replace('.', '').replace(',', ''))

def generate_city_link(burg, cells):
    name = burg['name']
    population = parse_population(str(burg.get('population', 0)))
    size = min(max(int(population/1000), 15), 60)  # Size between 15 and 60
    seed = random.randint(1, 2000000000)
    
    coast = 0
    river = 0
    try:
        cell = cells[burg['cell']]
        coast = 1 if cell.get('haven', 0) == 1 else 0
        river = 1 if cell.get('river', 0) else 0
    except (IndexError, KeyError):
        pass
    
    citadel = random.choice([0, 1])
    urban_castle = random.choice([0, 1])
    plaza = random.choice([0, 1])
    temple = random.choice([0, 1])
    walls = 1 if population > 5000 else random.choice([0, 1])
    shantytown = random.choice([0, 1])

    base_url = "https://watabou.github.io/city-generator/?"
    params = {
        "size": size,
        "seed": seed,
        "name": name.replace(" ", "+"),
        "greens": 0,
        "citadel": citadel,
        "urban_castle": urban_castle,
        "plaza": plaza,
        "temple": temple,
        "walls": walls,
        "shantytown": shantytown,
        "coast": coast,
        "river": river,
        "gates": -1
    }
    url = base_url + "&".join(f"{k}={v}" for k, v in params.items())
    return f'<iframe width="100%" height="500" src="{url}"></iframe>'

def generate_village_link(burg, cells):
    name = burg['name']
    population = parse_population(str(burg.get('population', 0)))
    seed = random.randint(1, 2000000000)
    
    river = ''
    try:
        cell = cells[burg['cell']]
        if cell.get('river', 0):
            river = 'river'
    except (IndexError, KeyError):
        pass
    
    tags = ['organic' if random.random() < 0.7 else 'gridded',
            'district' if random.random() < 0.3 else '',
            'no square' if random.random() < 0.5 else 'square',
            'isolated' if random.random() < 0.2 else '',
            'farmland' if random.random() < 0.8 else '',
            'dense' if random.random() < 0.3 else 'sparse',
            'grove' if random.random() < 0.5 else '']
    
    tags = [tag for tag in tags + [river] if tag]  # Remove empty strings

    base_url = "https://watabou.github.io/village-generator/?"
    params = {
        "seed": seed,
        "name": name.replace(" ", "+"),
        "pop": population,
        "tags": ",".join(tags)
    }
    url = base_url + "&".join(f"{k}={v}" for k, v in params.items())
    return f'<iframe width="100%" height="500" src="{url}"></iframe>'

def generate_dungeon_link(name):
    seed = random.randint(1, 2000000000)
    
    possible_tags = [
        "backdoor", "colonnades", "compact", "cramped", "deep", "dry", "dwelling",
        "flat", "flooded", "large", "medium", "no secrets", "ordered", "round",
        "single-level", "small", "spacious", "square", "string", "temple", "tomb",
        "treasure", "wet", "winding"
    ]
    
    num_tags = random.randint(2, 4)
    tags = random.sample(possible_tags, num_tags)
    
    base_url = "https://watabou.github.io/one-page-dungeon/?"
    params = {
        "seed": seed,
        "name": name.replace(" ", "+"),
        "tags": ",".join(tags)
    }
    url = base_url + "&".join(f"{k}={v}" for k, v in params.items())
    return f'<iframe width="100%" height="600" src="{url}"></iframe>'

def process_map_data(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    
    tiddlers = []

    culture_lookup = {c['i']: c['name'] for c in data['pack']['cultures']}
    state_lookup = {s['i']: s['name'] for s in data['pack']['states']}
    cells = data['pack'].get('cells', [])

    # General info
    info = data['info']
    general_info = f"""! Map Information
* Name: {info['mapName']}
* Size: {info['width']}x{info['height']}
* Seed: {info['seed']}
* Exported: {info['exportedAt']}
"""
    tiddlers.append(create_tiddler("Map Information", general_info, ["MapData"]))

    # Cultures
    for culture in data['pack']['cultures']:
        content = f"""! [[{culture['name']}]]
* Type: {culture.get('type', 'N/A')}
* Expansionism: {culture.get('expansionism', 'N/A')}
* Code: {culture.get('code', 'N/A')}
"""
        tiddlers.append(create_tiddler(f"Culture: {culture['name']}", content, ["Culture", "MapData"]))

    # States
    for state in data['pack']['states']:
        if state['i'] == 0:  # Skip neutral state
            continue
        content = f"""! [[{state['name']}]]
* Type: {state.get('type', 'N/A')}
* Expansionism: {state.get('expansionism', 'N/A')}
* Capital: [[{state_lookup.get(state.get('capital'), 'Unknown')}]]
* Form: {state.get('form', 'N/A')}
* Full Name: {state.get('fullName', 'N/A')}
"""
        tiddlers.append(create_tiddler(f"State: {state['name']}", content, ["State", "MapData"]))

    # Burgs
    for burg in data['pack']['burgs']:
        if burg.get('i', 0) == 0:  # Skip empty burg
            continue
        culture_name = culture_lookup.get(burg['culture'], 'Unknown')
        state_name = state_lookup.get(burg['state'], 'Unknown')
        population = parse_population(str(burg.get('population', 0)))
        content = f"""! [[{burg['name']}]]
* Population: {population:,}
* Type: {burg.get('type', 'N/A')}
* Culture: [[{culture_name}]]
* State: [[{state_name}]]
"""
        if population >= 1000:
            content += "\n" + generate_city_link(burg, cells)
        elif population > 0:
            content += "\n" + generate_village_link(burg, cells)
        
        tiddlers.append(create_tiddler(f"Burg: {burg['name']}", content, ["Burg", "MapData"]))

    # Religions
    for religion in data['pack']['religions']:
        if religion['i'] == 0:  # Skip no religion
            continue
        content = f"""! [[{religion['name']}]]
* Type: {religion.get('type', 'N/A')}
* Form: {religion.get('form', 'N/A')}
* Deity: {religion.get('deity', 'N/A')}
* Code: {religion.get('code', 'N/A')}
"""
        tiddlers.append(create_tiddler(f"Religion: {religion['name']}", content, ["Religion", "MapData"]))

    # Check for markers (which might include dungeon-like locations)
    if 'markers' in data['pack']:
        for marker in data['pack']['markers']:
            if marker['type'] in ['ruins', 'landmark', 'cave']:  # Add other relevant types
                name = marker.get('name', f"{marker['type'].capitalize()} at ({marker['x']}, {marker['y']})")
                content = f"""! [[{name}]]
* Type: {marker['type'].capitalize()}
* Location: x={marker.get('x', 'Unknown')}, y={marker.get('y', 'Unknown')}
* Description: {marker.get('description', 'No description available')}

{generate_dungeon_link(name)}
"""
                tiddlers.append(create_tiddler(f"{marker['type'].capitalize()}: {name}", content, [marker['type'], "MapData", "Dungeon"]))

    return tiddlers

def main():
    if len(sys.argv) != 2:
        print("Usage: python script_name.py <path_to_json_file>")
        sys.exit(1)

    file_path = sys.argv[1]
    if not os.path.exists(file_path):
        print(f"Error: File '{file_path}' not found.")
        sys.exit(1)

    tiddlers = process_map_data(file_path)

    # Save tiddlers to files
    output_folder = "tiddlers"
    os.makedirs(output_folder, exist_ok=True)

    for i, tiddler in enumerate(tiddlers):
        file_name = f"tiddler_{i+1}.tid"
        with open(os.path.join(output_folder, file_name), 'w', encoding='utf-8') as file:
            file.write(tiddler)

    print(f"Generated {len(tiddlers)} tiddlers in the '{output_folder}' directory.")

if __name__ == "__main__":
    main()