#!/usr/bin/env python3
"""Populate the test 1C extension dump with managed form learning fixtures."""

from __future__ import annotations

import hashlib
import json
import shutil
import uuid
from pathlib import Path


ROOT = Path(r"Z:\codex\1C\XML\UPO\Структура базы 1с\Расширения\test")
DONOR = Path(
    r"\\nas\MST\codex\1C\XML\UPO\Структура базы 1с\Расширения\фс_ДоработкиОбщее"
    r"\DataProcessors\фс_НастройкаУсловногоОформления"
)

OBJECT_NAME = "t_FORM_Probe"
OBJECT_UUID = "ae203d97-7a61-56d3-b1d0-f09bc7d83b21"
OBJECT_TYPE_ID = "5af4a44d-2c23-5329-afd1-16f3c9bc1602"
OBJECT_VALUE_ID = "d88b7e36-cdd5-53c8-b21d-431d863b5c79"
MANAGER_TYPE_ID = "60d06494-8efe-535e-9305-dbc33ae7c68d"
MANAGER_VALUE_ID = "c64a21a1-f344-50f0-ab4f-14603935586e"

FORMS = [
    {
        "name": "t_FORM_CommandBaseline",
        "uuid": "6a0b7e2c-49f6-5965-9100-2603d6be8eb2",
        "synonym": "FORM command baseline",
        "description": "Original command binding form copied from the donor.",
        "replacements": [],
    },
    {
        "name": "t_FORM_CommandLocalSwitch",
        "uuid": "cf77d8a3-6b09-590d-b51c-8796a72c37fa",
        "synonym": "FORM local command switch",
        "description": "Changes ФормаКомандаОбновить to Form.Command.КомандаПример1.",
        "replacements": [
            ("<CommandName>Form.Command.КомандаПрименить</CommandName>", "<CommandName>Form.Command.КомандаПример1</CommandName>"),
        ],
    },
    {
        "name": "t_FORM_CommandStandardSwitch",
        "uuid": "0c81571a-58bc-5d40-b91b-fbe01964809a",
        "synonym": "FORM standard command switch",
        "description": "Changes ТЗИзменитьФорму from standard CustomizeForm to Form.Command.КомандаПример1.",
        "replacements": [
            ("<CommandName>Form.StandardCommand.CustomizeForm</CommandName>", "<CommandName>Form.Command.КомандаПример1</CommandName>"),
        ],
    },
    {
        "name": "t_FORM_CommandAddedButtons",
        "uuid": "586eaf5e-23c7-5d97-8548-26e392bc7b3f",
        "synonym": "FORM added command buttons",
        "description": "Adds two extra buttons under Группа2 for local and standard command learning.",
        "replacements": [
            (
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример2\" id=\"63\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>\n"
                "\t\t\t\t\t\t\t\t\t<CommandName>Form.Command.КомандаПример2</CommandName>\n"
                "\t\t\t\t\t\t\t\t\t<ExtendedTooltip name=\"КомандаПример2РасширеннаяПодсказка\" id=\"64\"/>\n"
                "\t\t\t\t\t\t\t\t</Button>",
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример2\" id=\"63\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>\n"
                "\t\t\t\t\t\t\t\t\t<CommandName>Form.Command.КомандаПример2</CommandName>\n"
                "\t\t\t\t\t\t\t\t\t<ExtendedTooltip name=\"КомандаПример2РасширеннаяПодсказка\" id=\"64\"/>\n"
                "\t\t\t\t\t\t\t\t</Button>\n"
                "\t\t\t\t\t\t\t\t<Button name=\"УчебнаяКнопкаКомандаПример1\" id=\"101\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>\n"
                "\t\t\t\t\t\t\t\t\t<CommandName>Form.Command.КомандаПример1</CommandName>\n"
                "\t\t\t\t\t\t\t\t\t<ExtendedTooltip name=\"УчебнаяКнопкаКомандаПример1РасширеннаяПодсказка\" id=\"102\"/>\n"
                "\t\t\t\t\t\t\t\t</Button>\n"
                "\t\t\t\t\t\t\t\t<Button name=\"УчебнаяКнопкаСтандартнаяНастройка\" id=\"103\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>\n"
                "\t\t\t\t\t\t\t\t\t<CommandName>Form.StandardCommand.CustomizeForm</CommandName>\n"
                "\t\t\t\t\t\t\t\t\t<ExtendedTooltip name=\"УчебнаяКнопкаСтандартнаяНастройкаРасширеннаяПодсказка\" id=\"104\"/>\n"
                "\t\t\t\t\t\t\t\t</Button>",
            ),
        ],
    },
    {
        "name": "t_FORM_TopBarExpanded",
        "uuid": "0d69eaa2-937d-54b6-8951-24f0b37f819a",
        "synonym": "FORM top bar expanded buttons",
        "description": "Expands the self-closing form AutoCommandBar and adds local/standard command buttons.",
        "replacements": [
            (
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\"/>",
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\">\n"
                "\t\t<ChildItems>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаКомандаПример1\" id=\"105\">\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.Command.КомандаПример1</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаКомандаПример1РасширеннаяПодсказка\" id=\"106\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройка\" id=\"107\">\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.StandardCommand.CustomizeForm</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройкаРасширеннаяПодсказка\" id=\"108\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t</ChildItems>\n"
                "\t</AutoCommandBar>",
            ),
        ],
    },
    {
        "name": "t_FORM_TopBarCommandEdited",
        "uuid": "bbb7891d-3eb9-5c7a-93f8-d4ed551102ff",
        "synonym": "FORM top bar command edited",
        "description": "Expands the top command bar and swaps existing top button command bindings.",
        "replacements": [
            (
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\"/>",
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\">\n"
                "\t\t<ChildItems>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаКомандаПример1\" id=\"105\">\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.StandardCommand.CustomizeForm</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаКомандаПример1РасширеннаяПодсказка\" id=\"106\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройка\" id=\"107\">\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.Command.КомандаПример1</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройкаРасширеннаяПодсказка\" id=\"108\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t</ChildItems>\n"
                "\t</AutoCommandBar>",
            ),
        ],
    },
    {
        "name": "t_FORM_FieldVisualVariants",
        "uuid": "4fc3dacf-8c90-5f80-8b26-70cb7773c431",
        "synonym": "FORM field visual variants",
        "description": "Changes field width, height, multiline, and auto-max-width values for decoder learning.",
        "replacements": [
            ("<Width>5</Width>", "<Width>9</Width>"),
            ("<Width>5</Width>", "<Width>11</Width>"),
            (
                "\t\t\t\t\t\t\t\t\t<Width>5</Width>\n"
                "\t\t\t\t\t\t\t\t\t<ContextMenu name=\"ТЗК1КонтекстноеМеню\" id=\"34\"/>",
                "\t\t\t\t\t\t\t\t\t<Width>13</Width>\n"
                "\t\t\t\t\t\t\t\t\t<ContextMenu name=\"ТЗК1КонтекстноеМеню\" id=\"34\"/>",
            ),
            (
                "\t\t\t\t\t\t\t\t\t<Width>5</Width>\n"
                "\t\t\t\t\t\t\t\t\t<ContextMenu name=\"ТЗК2КонтекстноеМеню\" id=\"37\"/>",
                "\t\t\t\t\t\t\t\t\t<Width>15</Width>\n"
                "\t\t\t\t\t\t\t\t\t<ContextMenu name=\"ТЗК2КонтекстноеМеню\" id=\"37\"/>",
            ),
            (
                "\t\t\t\t\t\t\t\t\t<Width>5</Width>\n"
                "\t\t\t\t\t\t\t\t\t<AutoMaxWidth>false</AutoMaxWidth>",
                "\t\t\t\t\t\t\t\t\t<Width>17</Width>\n"
                "\t\t\t\t\t\t\t\t\t<AutoMaxWidth>false</AutoMaxWidth>",
            ),
            (
                "\t\t\t\t\t\t\t<AutoMaxWidth>false</AutoMaxWidth>\n"
                "\t\t\t\t\t\t\t<Height>8</Height>\n"
                "\t\t\t\t\t\t\t<MultiLine>true</MultiLine>",
                "\t\t\t\t\t\t\t<Width>19</Width>\n"
                "\t\t\t\t\t\t\t<AutoMaxWidth>false</AutoMaxWidth>\n"
                "\t\t\t\t\t\t\t<Height>12</Height>\n"
                "\t\t\t\t\t\t\t<MultiLine>true</MultiLine>",
            ),
        ],
    },
    {
        "name": "t_FORM_FieldBehaviorVariants",
        "uuid": "39eddfd9-2d50-5ff1-9a04-99b9bc8d4df2",
        "synonym": "FORM field behavior variants",
        "description": "Changes field visibility, availability, read-only, skip-on-input, and title location values.",
        "replacements": [
            (
                "\t\t\t\t\t\t\t\t<InputField name=\"А\" id=\"3\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>А</DataPath>",
                "\t\t\t\t\t\t\t\t<InputField name=\"А\" id=\"3\">\n"
                "\t\t\t\t\t\t\t\t\t<TitleLocation>None</TitleLocation>\n"
                "\t\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>А</DataPath>",
            ),
            (
                "\t\t\t\t\t\t\t\t<InputField name=\"Б\" id=\"6\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>Б</DataPath>",
                "\t\t\t\t\t\t\t\t<InputField name=\"Б\" id=\"6\">\n"
                "\t\t\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t\t\t<ReadOnly>true</ReadOnly>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>Б</DataPath>",
            ),
            (
                "\t\t\t\t\t\t\t\t<CheckBoxField name=\"ХочуКрасненького\" id=\"54\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ХочуКрасненького</DataPath>",
                "\t\t\t\t\t\t\t\t<CheckBoxField name=\"ХочуКрасненького\" id=\"54\">\n"
                "\t\t\t\t\t\t\t\t\t<SkipOnInput>true</SkipOnInput>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ХочуКрасненького</DataPath>",
            ),
            (
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗК1\" id=\"33\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.К1</DataPath>",
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗК1\" id=\"33\">\n"
                "\t\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.К1</DataPath>",
            ),
            (
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗК2\" id=\"36\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.К2</DataPath>",
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗК2\" id=\"36\">\n"
                "\t\t\t\t\t\t\t\t\t<ReadOnly>true</ReadOnly>\n"
                "\t\t\t\t\t\t\t\t\t<SkipOnInput>true</SkipOnInput>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.К2</DataPath>",
            ),
            (
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗПримечание\" id=\"48\">\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.Примечание</DataPath>",
                "\t\t\t\t\t\t\t\t<InputField name=\"ТЗПримечание\" id=\"48\">\n"
                "\t\t\t\t\t\t\t\t\t<TitleLocation>None</TitleLocation>\n"
                "\t\t\t\t\t\t\t\t\t<DataPath>ТЗ.Примечание</DataPath>",
            ),
            (
                "\t\t\t\t\t\t<InputField name=\"КодПрограммы\" id=\"12\">\n"
                "\t\t\t\t\t\t\t<DataPath>КодПрограммы</DataPath>",
                "\t\t\t\t\t\t<InputField name=\"КодПрограммы\" id=\"12\">\n"
                "\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t<ReadOnly>true</ReadOnly>\n"
                "\t\t\t\t\t\t\t<SkipOnInput>true</SkipOnInput>\n"
                "\t\t\t\t\t\t\t<DataPath>КодПрограммы</DataPath>",
            ),
        ],
    },
    {
        "name": "t_FORM_ButtonBehaviorVariants",
        "uuid": "a6af3267-8c83-5bc5-8fa8-1f77c0dbfd12",
        "synonym": "FORM button behavior variants",
        "description": "Changes usual and command-bar button visibility and availability values.",
        "replacements": [
            (
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\"/>",
                "\t<AutoCommandBar name=\"ФормаКоманднаяПанель\" id=\"-1\">\n"
                "\t\t<ChildItems>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаКомандаПример1\" id=\"105\">\n"
                "\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.Command.КомандаПример1</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаКомандаПример1РасширеннаяПодсказка\" id=\"106\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t\t<Button name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройка\" id=\"107\">\n"
                "\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t<Type>CommandBarButton</Type>\n"
                "\t\t\t\t<CommandName>Form.StandardCommand.CustomizeForm</CommandName>\n"
                "\t\t\t\t<ExtendedTooltip name=\"УчебнаяВерхняяКнопкаСтандартнаяНастройкаРасширеннаяПодсказка\" id=\"108\"/>\n"
                "\t\t\t</Button>\n"
                "\t\t</ChildItems>\n"
                "\t</AutoCommandBar>",
            ),
            (
                "\t\t\t\t\t\t\t\t\t<Button name=\"ТЗИзменитьФорму\" id=\"57\">\n"
                "\t\t\t\t\t\t\t\t\t\t<Type>CommandBarButton</Type>",
                "\t\t\t\t\t\t\t\t\t<Button name=\"ТЗИзменитьФорму\" id=\"57\">\n"
                "\t\t\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t\t\t\t<Type>CommandBarButton</Type>",
            ),
            (
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример1\" id=\"61\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>",
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример1\" id=\"61\">\n"
                "\t\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>",
            ),
            (
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример2\" id=\"63\">\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>",
                "\t\t\t\t\t\t\t\t<Button name=\"КомандаПример2\" id=\"63\">\n"
                "\t\t\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t\t\t<Type>UsualButton</Type>",
            ),
            (
                "\t\t\t\t\t\t<Button name=\"ФормаКомандаОбновить\" id=\"15\">\n"
                "\t\t\t\t\t\t\t<Type>UsualButton</Type>",
                "\t\t\t\t\t\t<Button name=\"ФормаКомандаОбновить\" id=\"15\">\n"
                "\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t<Type>UsualButton</Type>",
            ),
        ],
    },
    {
        "name": "t_FORM_ContainerTableBehaviorVariants",
        "uuid": "1283d22a-874e-58d2-8cd0-62cf9c29ac30",
        "synonym": "FORM container and table behavior variants",
        "description": "Changes group and table visibility/availability values for decoder learning.",
        "replacements": [
            (
                "\t\t\t\t\t</ToolTip>\n"
                "\t\t\t\t\t<Group>Vertical</Group>",
                "\t\t\t\t\t</ToolTip>\n"
                "\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t<Group>Vertical</Group>",
            ),
            (
                "\t\t\t\t\t\t<UsualGroup name=\"Группа1\" id=\"1\">\n"
                "\t\t\t\t\t\t\t<Group>HorizontalIfPossible</Group>",
                "\t\t\t\t\t\t<UsualGroup name=\"Группа1\" id=\"1\">\n"
                "\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t<Group>HorizontalIfPossible</Group>",
            ),
            (
                "\t\t\t\t\t\t<Table name=\"ТЗ\" id=\"20\">\n"
                "\t\t\t\t\t\t\t<Representation>List</Representation>",
                "\t\t\t\t\t\t<Table name=\"ТЗ\" id=\"20\">\n"
                "\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t<Representation>List</Representation>",
            ),
        ],
    },
    {
        "name": "t_FORM_TableAdditionsBehaviorVariants",
        "uuid": "bda8a247-cdf0-5be9-b186-df3a2f50650e",
        "synonym": "FORM table additions behavior variants",
        "description": "Changes table search/view-status/search-control addition visibility and availability values.",
        "replacements": [
            (
                "\t\t\t\t\t\t\t<SearchStringAddition name=\"ТЗСтрокаПоиска\" id=\"24\">\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
                "\t\t\t\t\t\t\t<SearchStringAddition name=\"ТЗСтрокаПоиска\" id=\"24\">\n"
                "\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
            ),
            (
                "\t\t\t\t\t\t\t<ViewStatusAddition name=\"ТЗСостояниеПросмотра\" id=\"27\">\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
                "\t\t\t\t\t\t\t<ViewStatusAddition name=\"ТЗСостояниеПросмотра\" id=\"27\">\n"
                "\t\t\t\t\t\t\t\t<Visible>false</Visible>\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
            ),
            (
                "\t\t\t\t\t\t\t<SearchControlAddition name=\"ТЗУправлениеПоиском\" id=\"30\">\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
                "\t\t\t\t\t\t\t<SearchControlAddition name=\"ТЗУправлениеПоиском\" id=\"30\">\n"
                "\t\t\t\t\t\t\t\t<Enabled>false</Enabled>\n"
                "\t\t\t\t\t\t\t\t<AdditionSource>",
            ),
        ],
    },
]

XMLNS = (
    'xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" '
    'xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" '
    'xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" '
    'xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" '
    'xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" '
    'xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" '
    'xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" '
    'xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" '
    'xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.21"'
)


def sha1(path: Path) -> str:
    return hashlib.sha1(path.read_bytes()).hexdigest()


def apply_replacements(text: str, replacements: list[tuple[str, str]]) -> str:
    result = text
    for old, new in replacements:
        if old not in result:
            raise ValueError(f"Could not find XML fragment: {old[:120]!r}")
        result = result.replace(old, new, 1)
    return result


def write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8", newline="\n")


def form_metadata_xml(form: dict[str, str]) -> str:
    return f'''<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject {XMLNS}>
\t<Form uuid="{form["uuid"]}">
\t\t<Properties>
\t\t\t<Name>{form["name"]}</Name>
\t\t\t<Synonym>
\t\t\t\t<v8:item>
\t\t\t\t\t<v8:lang>ru</v8:lang>
\t\t\t\t\t<v8:content>{form["synonym"]}</v8:content>
\t\t\t\t</v8:item>
\t\t\t</Synonym>
\t\t\t<Comment>{form["description"]}</Comment>
\t\t\t<FormType>Managed</FormType>
\t\t\t<IncludeHelpInContents>false</IncludeHelpInContents>
\t\t\t<UsePurposes>
\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>
\t\t\t</UsePurposes>
\t\t\t<UseInInterfaceCompatibilityMode>Any</UseInInterfaceCompatibilityMode>
\t\t\t<ExtendedPresentation/>
\t\t</Properties>
\t</Form>
</MetaDataObject>
'''


def object_metadata_xml() -> str:
    child_forms = "\n".join(f"\t\t\t<Form>{form['name']}</Form>" for form in FORMS)
    return f'''<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject {XMLNS}>
\t<DataProcessor uuid="{OBJECT_UUID}">
\t\t<InternalInfo>
\t\t\t<xr:GeneratedType name="DataProcessorObject.{OBJECT_NAME}" category="Object">
\t\t\t\t<xr:TypeId>{OBJECT_TYPE_ID}</xr:TypeId>
\t\t\t\t<xr:ValueId>{OBJECT_VALUE_ID}</xr:ValueId>
\t\t\t</xr:GeneratedType>
\t\t\t<xr:GeneratedType name="DataProcessorManager.{OBJECT_NAME}" category="Manager">
\t\t\t\t<xr:TypeId>{MANAGER_TYPE_ID}</xr:TypeId>
\t\t\t\t<xr:ValueId>{MANAGER_VALUE_ID}</xr:ValueId>
\t\t\t</xr:GeneratedType>
\t\t</InternalInfo>
\t\t<Properties>
\t\t\t<Name>{OBJECT_NAME}</Name>
\t\t\t<Synonym>
\t\t\t\t<v8:item>
\t\t\t\t\t<v8:lang>ru</v8:lang>
\t\t\t\t\t<v8:content>FORM probe</v8:content>
\t\t\t\t</v8:item>
\t\t\t</Synonym>
\t\t\t<Comment>Generated form fixtures for SQL/XML decoder learning.</Comment>
\t\t\t<UseStandardCommands>false</UseStandardCommands>
\t\t\t<DefaultForm>DataProcessor.{OBJECT_NAME}.Form.{FORMS[0]["name"]}</DefaultForm>
\t\t\t<AuxiliaryForm/>
\t\t\t<IncludeHelpInContents>false</IncludeHelpInContents>
\t\t\t<ExtendedPresentation/>
\t\t\t<Explanation/>
\t\t</Properties>
\t\t<ChildObjects>
{child_forms}
\t\t</ChildObjects>
\t</DataProcessor>
</MetaDataObject>
'''


FORM_MODULE = """&НаКлиенте
Процедура ПриОткрытии(Отказ)
КонецПроцедуры

&НаКлиенте
Процедура КомандаПрименить(Команда)
КонецПроцедуры

&НаКлиенте
Процедура КодПрограммыИзменениеТекстаРедактирования(Элемент, Текст, СтандартнаяОбработка)
КонецПроцедуры

&НаКлиенте
Процедура КомандаПример1(Команда)
КонецПроцедуры

&НаКлиенте
Процедура КомандаПример2(Команда)
КонецПроцедуры

&НаСервере
Процедура ПередЗагрузкойДанныхИзНастроекНаСервере(Настройки)
КонецПроцедуры
"""


def update_configuration() -> None:
    path = ROOT / "Configuration.xml"
    text = path.read_text(encoding="utf-8-sig")
    marker = f"\t\t\t<DataProcessor>{OBJECT_NAME}</DataProcessor>\n"
    text = text.replace(marker, "")
    insert_before = "\t\t\t<CommonTemplate>"
    if insert_before not in text:
        raise ValueError("Could not find CommonTemplate insertion point in Configuration.xml")
    text = text.replace(insert_before, marker + insert_before, 1)
    write_text(path, text)


def update_dumpinfo(files: dict[str, Path]) -> None:
    path = ROOT / "ConfigDumpInfo.xml"
    text = path.read_text(encoding="utf-8-sig")
    lines = text.splitlines()
    filtered = [line for line in lines if f'DataProcessor.{OBJECT_NAME}' not in line]
    entries = [
        f'\t\t<Metadata name="DataProcessor.{OBJECT_NAME}" id="{OBJECT_UUID}" configVersion="{sha1(files["object"])}"/>',
        f'\t\t<Metadata name="DataProcessor.{OBJECT_NAME}.ObjectModule" id="{OBJECT_UUID}.0" configVersion="{sha1(files["object_module"])}"/>',
    ]
    for form in FORMS:
        form_key = f"form:{form['name']}"
        payload_key = f"payload:{form['name']}"
        entries.extend(
            [
                f'\t\t<Metadata name="DataProcessor.{OBJECT_NAME}.Form.{form["name"]}" id="{form["uuid"]}" configVersion="{sha1(files[form_key])}"/>',
                f'\t\t<Metadata name="DataProcessor.{OBJECT_NAME}.Form.{form["name"]}.Form" id="{form["uuid"]}.0" configVersion="{sha1(files[payload_key])}"/>',
            ]
        )
    try:
        index = next(i for i, line in enumerate(filtered) if 'Metadata name="Configuration.test"' in line)
    except StopIteration as exc:
        raise ValueError("Could not find Configuration.test insertion point in ConfigDumpInfo.xml") from exc
    filtered[index:index] = entries
    write_text(path, "\n".join(filtered) + "\n")


def main() -> int:
    if not ROOT.is_dir():
        raise FileNotFoundError(ROOT)
    source_form = (DONOR / "Forms" / "ТестНастройки" / "Ext" / "Form.xml").read_text(encoding="utf-8-sig")
    source_form = source_form.replace("cfg:DataProcessorObject.фс_НастройкаУсловногоОформления", f"cfg:DataProcessorObject.{OBJECT_NAME}")
    target = ROOT / "DataProcessors" / OBJECT_NAME
    if target.exists():
        shutil.rmtree(target)
    target.mkdir(parents=True)

    files: dict[str, Path] = {}
    object_xml = ROOT / "DataProcessors" / f"{OBJECT_NAME}.xml"
    write_text(object_xml, object_metadata_xml())
    files["object"] = object_xml
    object_module = target / "Ext" / "ObjectModule.bsl"
    write_text(object_module, "// Generated test data processor for form decoder learning.\n")
    files["object_module"] = object_module

    for form in FORMS:
        form_xml = target / "Forms" / f"{form['name']}.xml"
        payload = target / "Forms" / form["name"] / "Ext" / "Form.xml"
        module = target / "Forms" / form["name"] / "Ext" / "Form" / "Module.bsl"
        write_text(form_xml, form_metadata_xml(form))
        write_text(payload, apply_replacements(source_form, form["replacements"]))
        write_text(module, FORM_MODULE)
        files[f"form:{form['name']}"] = form_xml
        files[f"payload:{form['name']}"] = payload
        files[f"module:{form['name']}"] = module

    update_configuration()
    update_dumpinfo(files)
    manifest = {
        "schema": "onec_test_extension_form_fixtures.v1",
        "root": str(ROOT),
        "data_processor": f"DataProcessor.{OBJECT_NAME}",
        "forms": [
            {
                "name": form["name"],
                "uuid": form["uuid"],
                "description": form["description"],
                "form_xml": str(target / "Forms" / form["name"] / "Ext" / "Form.xml"),
            }
            for form in FORMS
        ],
    }
    manifest_path = target / "form-fixtures.manifest.json"
    write_text(manifest_path, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
    print(json.dumps({"status": "ok", "manifest": str(manifest_path), "forms": len(FORMS)}, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
