# Three exterior angles and circulation/interior slices for a verified individual-building pair.
import argparse
import json
import subprocess
import sys
from pathlib import Path
from hearth.persistence import load_scene, companion_path
from examples.preview import render, CUTAWAY


def preview(source, output, seed, size=1200):
    scene = load_scene(source)
    if scene.seed != seed:
        raise ValueError('Explicit seed does not match artifact')
    output.mkdir(parents=True, exist_ok=True)
    records = []
    for label, azimuth, elevation in (('front', 215, 28), ('rear', 35, 28), ('side', 120, 26)):
        target = output / (label + '.png')
        render(source, target, azimuth, elevation, size, 3.4)
        records.append({'label': label, 'image': str(target), 'azimuth': azimuth, 'elevation': elevation, 'complete': True})
    building = next(n for n in scene.nodes.values() if n.type == 'building.rooms')
    floor = building.frame.origin[1] + building.contract.decisions['floor']
    offset = json.loads(companion_path(source).read_text())['offset']
    cuts = [('interior', 'y', floor + 2 - offset[1], 215, 66)]
    stairs = [n for n in scene.nodes.values() if n.type == 'circulation.stair']
    if stairs:
        cells = scene.cells(stairs[0].path)
        axis = min((0, 2), key=lambda k: max(p[k] for p in cells) - min(p[k] for p in cells))
        cut = max(p[axis] for p in cells) + 1 - offset[axis]
        cuts.append(('circulation', 'xz'[axis // 2], cut, 110 if axis == 0 else 20, 26))
    for label, axis, limit, azimuth, elevation in cuts:
        cut = output / (label + '.litematic')
        subprocess.run([sys.executable, str(CUTAWAY), '--input', str(source), '--output', str(cut), '--axis', axis, '--max', str(limit), '--name', label], check=True)
        target = output / (label + '.png')
        render(cut, target, azimuth, elevation, size, 3.2)
        records.append({'label': label, 'image': str(target), 'axis': axis, 'limit_export_local': limit, 'azimuth': azimuth, 'elevation': elevation, 'geometry_only_cutaway': True})
    manifest = {'source': str(source), 'seed': seed, 'views': records}
    (output / 'views.json').write_text(json.dumps(manifest, indent=2))
    return manifest


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=0)
    parser.add_argument('--input', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--size', type=int, default=1200)
    args = parser.parse_args()
    preview(args.input, args.output, args.seed, args.size)
