import difflib,sys
from pathlib import Path

store=Path(sys.argv[1]);output=Path(sys.argv[2]);output.mkdir(mode=0o700,exist_ok=True)
helper='''    private function normalizeDictionaryCreateTime(array $row): array
    {
        if (ltrim((string)config('database.type'), '\\\\') !== \\app\\cores\\database\\Dm::class) {
            return $row;
        }
        $value = $row['create_time'] ?? null;
        if (is_string($value)
            && preg_match('/^((\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}))\\.0{1,6}$/D', $value, $match)
            && (int)$match[2] >= 1000 && checkdate((int)$match[3], (int)$match[4], (int)$match[2])
            && (int)$match[5] <= 23 && (int)$match[6] <= 59 && (int)$match[7] <= 59) {
            $row['create_time'] = $match[1];
        }
        return $row;
    }

'''
spec={
'p/logic/Nutrition.php': [('''            foreach ($nutrition as $key => $value) {
                $nutrition[$key]['img_path']''','''            foreach ($nutrition as $key => $value) {
                $nutrition[$key] = $this->normalizeDictionaryCreateTime($value);
                $nutrition[$key]['img_path']''')],
'm/logic/Nutrition.php': [('''            foreach ($rand_data as $key => $value) {
                $rand_data[$key]['img_path']''','''            foreach ($rand_data as $key => $value) {
                $rand_data[$key] = $this->normalizeDictionaryCreateTime($value);
                $rand_data[$key]['img_path']''')]
}
patch=[]
for relative,replacements in spec.items():
    old=(store/'application'/relative).read_text();new=old
    for a,b in replacements:
        assert new.count(a)==1,(relative,new.count(a));new=new.replace(a,b)
    anchor='''    public function info($uuid) {
        $nutrition = $this->model->read($uuid);
'''
    change=anchor+'''        if (is_array($nutrition)) {
            $nutrition = $this->normalizeDictionaryCreateTime($nutrition);
        }
'''
    assert new.count(anchor)==1;new=new.replace(anchor,change)
    if relative.startswith('m/'):
        index=new.rfind('\n}');assert index>0;new=new[:index]+'\n'+helper+new[index:]
    label=relative[0].upper()+'-Nutrition.php';(output/label).write_text(new)
    patch.extend(difflib.unified_diff(old.splitlines(True),new.splitlines(True),fromfile='a/application/'+relative,tofile='b/application/'+relative))
(output/'nutrition-product-read10.patch').write_text(''.join(patch));print('Two isolated source candidates and narrow patch created')
