File size: 7,149 Bytes
213c234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46ce65
 
213c234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { PicletInstance } from '$lib/db/schema';

const METADATA_KEY = 'snaplings-piclet-v1';

interface PicletMetadata {
  version: 1;
  data: Omit<PicletInstance, 'id' | 'rosterPosition' | 'isInRoster' | 'caughtAt'>;
  checksum?: string;
}

/**
 * Extract piclet metadata from a PNG image
 */
export async function extractPicletMetadata(file: File): Promise<PicletInstance | null> {
  try {
    const arrayBuffer = await file.arrayBuffer();
    const bytes = new Uint8Array(arrayBuffer);
    
    // Check PNG signature
    if (!isPNG(bytes)) {
      return null;
    }
    
    // Find tEXt chunks
    const chunks = parsePNGChunks(bytes);
    const textChunk = chunks.find(chunk => 
      chunk.type === 'tEXt' && 
      chunk.keyword === METADATA_KEY
    );
    
    if (!textChunk || !textChunk.text) {
      return null;
    }
    
    // Parse metadata
    const metadata: PicletMetadata = JSON.parse(textChunk.text);
    
    // Validate version
    if (metadata.version !== 1) {
      console.warn('Unsupported piclet metadata version:', metadata.version);
      return null;
    }
    
    // Create PicletInstance from metadata
    const piclet: PicletInstance = {
      ...metadata.data,
      caughtAt: new Date(), // Use current date for import
      isInRoster: false,
      rosterPosition: undefined
    };
    
    return piclet;
  } catch (error) {
    console.error('Failed to extract piclet metadata:', error);
    return null;
  }
}

/**
 * Embed piclet metadata into a PNG image
 */
export async function embedPicletMetadata(imageBlob: Blob, piclet: PicletInstance): Promise<Blob> {
  const arrayBuffer = await imageBlob.arrayBuffer();
  const bytes = new Uint8Array(arrayBuffer);
  
  // Prepare metadata
  const metadata: PicletMetadata = {
    version: 1,
    data: {
      typeId: piclet.typeId,
      nickname: piclet.nickname,
      primaryType: piclet.primaryType,
      secondaryType: piclet.secondaryType,
      currentHp: piclet.maxHp, // Reset to full HP for sharing
      maxHp: piclet.maxHp,
      level: piclet.level,
      xp: piclet.xp,
      attack: piclet.attack,
      defense: piclet.defense,
      fieldAttack: piclet.fieldAttack,
      fieldDefense: piclet.fieldDefense,
      speed: piclet.speed,
      baseHp: piclet.baseHp,
      baseAttack: piclet.baseAttack,
      baseDefense: piclet.baseDefense,
      baseFieldAttack: piclet.baseFieldAttack,
      baseFieldDefense: piclet.baseFieldDefense,
      baseSpeed: piclet.baseSpeed,
      moves: piclet.moves,
      nature: piclet.nature,
      bst: piclet.bst,
      tier: piclet.tier,
      role: piclet.role,
      variance: piclet.variance,
      imageUrl: piclet.imageUrl,
      imageData: piclet.imageData,
      imageCaption: piclet.imageCaption,
      concept: piclet.concept,
      imagePrompt: piclet.imagePrompt
    }
  };
  
  // Create tEXt chunk
  const textChunk = createTextChunk(METADATA_KEY, JSON.stringify(metadata));
  
  // Insert chunk after IHDR
  const newBytes = insertChunkAfterIHDR(bytes, textChunk);
  
  return new Blob([newBytes], { type: 'image/png' });
}

/**
 * Check if bytes represent a PNG file
 */
function isPNG(bytes: Uint8Array): boolean {
  const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];
  if (bytes.length < 8) return false;
  
  for (let i = 0; i < 8; i++) {
    if (bytes[i] !== pngSignature[i]) return false;
  }
  
  return true;
}

/**
 * Parse PNG chunks
 */
function parsePNGChunks(bytes: Uint8Array): any[] {
  const chunks = [];
  let pos = 8; // Skip PNG signature
  
  while (pos < bytes.length) {
    // Read chunk length
    const length = readUInt32BE(bytes, pos);
    pos += 4;
    
    // Read chunk type
    const type = String.fromCharCode(...bytes.slice(pos, pos + 4));
    pos += 4;
    
    // Read chunk data
    const data = bytes.slice(pos, pos + length);
    pos += length;
    
    // Skip CRC
    pos += 4;
    
    // Parse tEXt chunks
    if (type === 'tEXt') {
      const nullIndex = data.indexOf(0);
      if (nullIndex !== -1) {
        const keyword = String.fromCharCode(...data.slice(0, nullIndex));
        const text = String.fromCharCode(...data.slice(nullIndex + 1));
        chunks.push({ type, keyword, text });
      }
    } else {
      chunks.push({ type, data });
    }
    
    if (type === 'IEND') break;
  }
  
  return chunks;
}

/**
 * Create a tEXt chunk
 */
function createTextChunk(keyword: string, text: string): Uint8Array {
  const keywordBytes = new TextEncoder().encode(keyword);
  const textBytes = new TextEncoder().encode(text);
  
  // Create chunk data: keyword + null + text
  const data = new Uint8Array(keywordBytes.length + 1 + textBytes.length);
  data.set(keywordBytes);
  data[keywordBytes.length] = 0; // null separator
  data.set(textBytes, keywordBytes.length + 1);
  
  // Create full chunk: length + type + data + crc
  const chunk = new Uint8Array(4 + 4 + data.length + 4);
  
  // Length
  writeUInt32BE(chunk, 0, data.length);
  
  // Type: 'tEXt'
  chunk[4] = 116; // t
  chunk[5] = 69;  // E
  chunk[6] = 88;  // X
  chunk[7] = 116; // t
  
  // Data
  chunk.set(data, 8);
  
  // CRC
  const crc = calculateCRC(chunk.slice(4, 8 + data.length));
  writeUInt32BE(chunk, 8 + data.length, crc);
  
  return chunk;
}

/**
 * Insert chunk after IHDR
 */
function insertChunkAfterIHDR(bytes: Uint8Array, newChunk: Uint8Array): Uint8Array {
  // Find IHDR chunk end
  let ihdrEnd = 8; // PNG signature
  ihdrEnd += 4; // IHDR length
  ihdrEnd += 4; // IHDR type
  const ihdrLength = readUInt32BE(bytes, 8);
  ihdrEnd += ihdrLength; // IHDR data
  ihdrEnd += 4; // IHDR CRC
  
  // Create new array
  const result = new Uint8Array(bytes.length + newChunk.length);
  
  // Copy up to IHDR end
  result.set(bytes.slice(0, ihdrEnd));
  
  // Insert new chunk
  result.set(newChunk, ihdrEnd);
  
  // Copy rest
  result.set(bytes.slice(ihdrEnd), ihdrEnd + newChunk.length);
  
  return result;
}

/**
 * Read 32-bit unsigned integer (big endian)
 */
function readUInt32BE(bytes: Uint8Array, offset: number): number {
  return (bytes[offset] << 24) | 
         (bytes[offset + 1] << 16) | 
         (bytes[offset + 2] << 8) | 
         bytes[offset + 3];
}

/**
 * Write 32-bit unsigned integer (big endian)
 */
function writeUInt32BE(bytes: Uint8Array, offset: number, value: number): void {
  bytes[offset] = (value >>> 24) & 0xff;
  bytes[offset + 1] = (value >>> 16) & 0xff;
  bytes[offset + 2] = (value >>> 8) & 0xff;
  bytes[offset + 3] = value & 0xff;
}

/**
 * Calculate CRC32 for PNG chunk
 */
function calculateCRC(bytes: Uint8Array): number {
  const crcTable = getCRCTable();
  let crc = 0xffffffff;
  
  for (let i = 0; i < bytes.length; i++) {
    crc = crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
  }
  
  return crc ^ 0xffffffff;
}

/**
 * Get CRC table (cached)
 */
let crcTable: Uint32Array | null = null;
function getCRCTable(): Uint32Array {
  if (crcTable) return crcTable;
  
  crcTable = new Uint32Array(256);
  for (let i = 0; i < 256; i++) {
    let c = i;
    for (let j = 0; j < 8; j++) {
      c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    }
    crcTable[i] = c;
  }
  
  return crcTable;
}