"""Standalone Kufar UI, 2026.11.10.8 / 10.11.2026 MSK."""
import json
import logging
import sqlite3
import xml.etree.ElementTree as ET
from datetime import datetime
from urllib.parse import urlencode
from zoneinfo import ZoneInfo

from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import RedirectResponse, Response

from . import kufar, kufarstock, webdb

log = logging.getLogger(__name__)


def install(app, db, require_user, templates, header_menu_flags, root):
    router = APIRouter()

    def access(request, write=False, settings=False):
        uid = require_user(request)
        with db(uid) as conn:
            user = webdb.current_user(conn, uid)
            if write and webdb.is_read_only(user):
                raise HTTPException(403, "Недостаточно прав для изменения объявлений")
            if settings and not webdb.has_perm(conn, "reference.write"):
                raise HTTPException(403, "Настройка хостинга доступна администратору справочников")
        return uid

    def redirect(message, error=False, unid=""):
        return RedirectResponse("/kufar?" + urlencode({"view":"feed", "error" if error else "message": message, "item": unid}), status_code=303)

    def inventory_data(uid):
        with kufar.connect(root) as local:
            kufarstock.import_snapshot(local,root/'prepared/2026-11-04/all-positions.json',uid)
            source,rows=kufarstock.load(local)
            feed_by_product={r['product_id']:r['unid'] for r in kufar.snapshot(local)['rows'] if r['product_id']}
            live_scan=kufarstock.load_live_scan(local)
            new_ads,removed_ads=kufarstock.compare_live(rows,live_scan)
        product_ids={r['product_id'] for r in rows if r['product_id']}|{r['product_id'] for r in new_ads if r['product_id']}
        with db(uid) as conn:
            products={r['product_id']:r for r in conn.execute("SELECT product_id,product_name,is_active,grade,description,site_price,discount_percent,source_snapshot_at FROM app.discount_product WHERE product_id=ANY(%s)", (list(product_ids),)).fetchall()}
            latest=conn.execute("SELECT max(source_snapshot_at) AS at FROM app.discount_sync").fetchone()['at']
        rows=kufarstock.reconcile(rows,products)
        for row in rows:
            row['feed_unid']=feed_by_product.get(row['product_id'],'')
            row['price_check']=kufarstock.price_check(row['live_price'],row['product']['site_price'] if row['product'] else None)
        for row in new_ads:
            row['product']=products.get(row['product_id'])
            row['price_check']=kufarstock.price_check(row['price'],row['product']['site_price'] if row['product'] else None)
        price_rows=[r for r in rows if r['live_status']=='current' and r['price_check']['status']=='different']
        price_rows.extend(r for r in new_ads if r['price_check']['status']=='different')
        checked=sum(r['live_status']=='current' and r['price_check']['status']!='unknown' for r in rows)
        checked+=sum(r['price_check']['status']!='unknown' for r in new_ads)
        return source,rows,latest,live_scan,new_ads,removed_ads,price_rows,checked

    def inventory_page(request,uid,ad_id,q,stock,cat,prepared,proposal,section,page,message,error):
        section='inventory' if ad_id else section if section in {'overview','inventory'} else 'overview'
        source,all_rows,latest,live_scan,new_ads,removed_ads,price_rows,price_checked=inventory_data(uid)
        pending_local=[r for r in all_rows if r['local_removed'] and r.get('live_status')=='current']
        selected=next((r for r in all_rows if r['ad_id']==ad_id),None)
        filtered=[r for r in all_rows if (not q or q.casefold() in (r['ad_id']+' '+r['title']+' '+r['body']+' '+r['product_id']).casefold()) and (not cat or r['category']==cat) and (not stock or (r['duplicate'] if stock=='duplicate' else r['stock']==stock)) and (not prepared or (r['included'] if prepared=='yes' else not r['included']))]
        total=len(filtered);pages=max(1,(total+39)//40);page=max(1,min(page,pages))
        with db(uid) as conn:
            user=webdb.current_user(conn,uid);units=webdb.accessible_units(conn)
            ctx=dict(user=user,units=units,unit=units[0] if units else None,mode='kufar',title='Куфар',can_edit=not webdb.is_read_only(user))
            ctx.update(header_menu_flags(conn,units))
        def stamp(value):
            if not value:return 'не выполнялась'
            dt=datetime.fromisoformat(value) if isinstance(value,str) else value
            return dt.astimezone(ZoneInfo('Europe/Moscow')).strftime('%d.%m.%Y %H:%M:%S МСК')
        def url(**changes):
            values=dict(q=q,stock=stock,cat=cat,prepared=prepared,proposal=proposal,section=section,page=page,ad=ad_id);values.update(changes)
            return '/kufar?'+urlencode({k:v for k,v in values.items() if v})
        ctx.update(source=source,all_count=len(all_rows),rows=filtered[(page-1)*40:page*40],selected=selected,
                   total=total,pages=pages,page=page,q=q,stock=stock,cat=cat,prepared=prepared,
                   categories=sorted({r['category'] for r in all_rows}),latest=latest,
                   present=sum(r['stock']=='present' for r in all_rows),missing=sum(r['stock']=='missing' for r in all_rows),
                   no_code=sum(r['stock']=='no_code' for r in all_rows),unknown=sum(r['stock']=='unknown' for r in all_rows),
                   duplicates=sum(r['duplicate'] for r in all_rows),included=sum(r['included'] for r in all_rows),
                   available=sum(r['public_status']=='available' for r in all_rows),unavailable=sum(r['public_status']=='unavailable' for r in all_rows),
                   local_removed=sum(bool(r['local_removed']) and not r['archived'] for r in all_rows),
                   archived_count=sum(bool(r['archived']) for r in all_rows),
                   local_changed=sum(bool(r['local_changed']) for r in all_rows),
                   full_file_count=sum(not r['local_removed'] and not r['archived'] for r in all_rows),
                   compared_at=max((r['compared_at'] for r in all_rows if r['compared_at']),default=None),
                   live_scan=live_scan,profile_url=(live_scan or {}).get('profile_url',kufarstock.DEFAULT_PROFILE_URL),
                   new_ads=new_ads,removed_ads=removed_ads,pending_local=pending_local,
                   price_rows=price_rows,price_checked=price_checked,
                   proposal=proposal,section=section,standard_text=kufar.STANDARD_DESCRIPTION_TEXT,
                   stamp=stamp,url=url,message=message,error=error)
        return templates.TemplateResponse(request,'kufar_inventory.html',ctx)

    def perform(request, callback, *, settings=False, unid=""):
        uid = access(request, True, settings)
        try:
            with kufar.connect(root) as conn:
                message = callback(conn, uid)
            return redirect(message or "Изменения сохранены.", unid=unid)
        except kufar.Error as exc:
            return redirect(str(exc), True, unid)
        except sqlite3.OperationalError:
            return redirect("Раздел занят другой операцией. Повторите после её завершения.", True, unid)
        except Exception:
            # Do not include server responses: they can contain credentials or paths.
            log.warning("Kufar operation failed (%s)", __import__('sys').exc_info()[0].__name__)
            return redirect("Операция не подтверждена. Проверьте параметры подключения, доступ к файлу и выполните сверку. Локальные изменения сохранены.", True, unid)

    @router.get("/kufar")
    def page(request: Request, item: str = "", q: str = "", warnings: str = "", message: str = "", error: str = "", category: str = "", view: str = "", ad: str = "", stock: str = "", cat: str = "", prepared: str = "", proposal: str = "", section: str = "overview", new_product_id: str = "", page: int = 1):
        uid = access(request)
        if view!='feed':
            return inventory_page(request,uid,ad,q,stock,cat,prepared,proposal,section,page,message,error)
        with kufar.connect(root) as local:
            s = kufar.snapshot(local)
            live_scan = kufarstock.load_live_scan(local)
            events = [dict(r) for r in local.execute("SELECT * FROM event ORDER BY id DESC LIMIT 15")]
        candidate_report=None
        candidate_path=root/'candidate'/'report.json'
        if candidate_path.exists():
            try:candidate_report=json.loads(candidate_path.read_text(encoding='utf-8'))
            except (OSError,ValueError):candidate_report=None
        config = dict(s["config"])
        has_password = bool(config.pop("secret", ""))
        records = kufar.parse(s["baseline"])[1] if s["baseline"] else {}
        remote_count = len(records)
        for row in s["rows"]:
            if row["source_xml"]:
                records[row["unid"]] = ET.fromstring(row["source_xml"])
        rows = []
        with db(uid) as conn:
            user = webdb.current_user(conn, uid)
            units = webdb.accessible_units(conn)
            products = {r["product_id"]: r for r in conn.execute("SELECT product_id,product_name,is_active,site_price,source_snapshot_at FROM app.discount_product WHERE product_id = ANY(%s)", ([r["product_id"] for r in s["rows"] if r["product_id"]],)).fetchall()}
            latest = conn.execute("SELECT max(source_snapshot_at) AS at FROM app.discount_sync").fetchone()["at"]
            discount_prefill = None
            if new_product_id:
                discount_prefill = conn.execute("SELECT product_id,product_name,description,site_price,category_2,category_4 FROM app.discount_product WHERE product_id=%s AND is_active", (new_product_id,)).fetchone()
            ctx = {"user": user, "units": units, "unit": units[0] if units else None,
                   "mode": "kufar", "title": "Куфар", "can_edit": not webdb.is_read_only(user)}
            ctx.update(header_menu_flags(conn, units))
        for row in s["rows"]:
            base = kufar.fields(records[row["unid"]])
            row.update(json.loads(row["draft"]) if row["draft"] else base)
            product = products.get(row["product_id"])
            row["stock"] = "missing" if product and not product["is_active"] else "present" if product else "unknown"
            row["stock_label"] = {"missing": "Нет в остатке — проверить снятие", "present": "Есть в срезе уценки", "unknown": "Не сопоставлено с уценкой"}[row["stock"]]
            row["changed"] = bool(row["draft"] or row["removed"] or row["source_xml"])
            rows.append(row)
        selected = next((r for r in rows if r["unid"] == item), None)
        filtered = [r for r in rows if (not q or q.casefold() in (r["unid"] + " " + r["subject"] + " " + r["product_id"]).casefold()) and (not warnings or r["stock"] != "present")]
        stock_report = kufarstock.feed_stock_review(s["rows"], records, products) if s["baseline"] else None
        def stamp(value):
            if not value:
                return "ещё не выполнялась"
            dt = datetime.fromisoformat(value) if isinstance(value, str) else value
            return dt.astimezone(ZoneInfo("Europe/Moscow")).strftime("%d.%m.%Y %H:%M:%S МСК")
        planned=sum(not r["removed"] for r in rows)
        active_total=live_scan['total'] if live_scan else ((s['manual_count'] or 0)+remote_count if s['manual_count'] is not None else None)
        projected_total=(active_total+planned-remote_count) if active_total is not None else None
        ctx.update(state=s, config=config, has_password=has_password, rows=filtered, selected=selected,
                   total=remote_count, planned=planned, changes=sum(r["changed"] for r in rows),
                   missing=sum(r["stock"] == "missing" and not r["removed"] for r in rows),
                   unknown=sum(r["stock"] == "unknown" for r in rows), q=q, warnings=warnings,
                   message=message, error=error, events=events, stamp=stamp, latest=latest,
                   categories=kufar.categories(), category=category, live_scan=live_scan,
                   standard_text=kufar.STANDARD_DESCRIPTION_TEXT,
                   active_total=active_total, projected_total=projected_total,
                   candidate_report=candidate_report, stock_report=stock_report)
        ctx['discount_prefill']=dict(discount_prefill) if discount_prefill else None
        ctx['new_product_id']=new_product_id
        return templates.TemplateResponse(request, "kufar.html", ctx)

    @router.post('/kufar/inventory/bind')
    def inventory_bind(request: Request, ad_id: str=Form(...), version: int=Form(...), product_id: str=Form('')):
        uid=access(request,True)
        try:
            with kufar.connect(root) as conn:
                kufarstock.bind(conn,ad_id,version,product_id,uid)
            values=dict(section='inventory',ad=ad_id,message='Привязка сохранена. Остаток пересчитан по точному коду; объявление на Kufar не изменено.')
        except kufar.Error as exc:values=dict(section='inventory',ad=ad_id,error=str(exc))
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.get('/kufar/inventory/product-search')
    def inventory_product_search(request: Request,q: str=''):
        uid=access(request)
        q=q.strip()
        if len(q)<2:
            return Response('[]',media_type='application/json')
        pattern='%'+q.replace('%','\\%').replace('_','\\_')+'%'
        with db(uid) as conn:
            rows=conn.execute("""SELECT product_id,product_name,site_price,is_active
                FROM app.discount_product
                WHERE product_id ILIKE %s ESCAPE '\\' OR product_name ILIKE %s ESCAPE '\\'
                ORDER BY (product_id=%s) DESC,is_active DESC,product_name LIMIT 20""",
                (pattern,pattern,q)).fetchall()
        return Response(json.dumps([dict(row) for row in rows],ensure_ascii=False,default=str),media_type='application/json')

    @router.post('/kufar/inventory/save')
    def inventory_save(request: Request,ad_id: str=Form(...),version: int=Form(...),title: str=Form(''),body: str=Form(''),price: str=Form(''),photos: str=Form('')):
        uid=access(request,True)
        try:
            with kufar.connect(root) as conn:
                kufarstock.save_local(conn,ad_id,version,title,body,price,photos.splitlines(),uid)
            values=dict(section='inventory',ad=ad_id,message='Карточка сохранена локально без обязательной привязки к уценке. Изменения войдут в следующий полный файл.')
        except kufar.Error as exc:
            values=dict(section='inventory',ad=ad_id,error=str(exc))
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post('/kufar/inventory/archive')
    def inventory_archive(request: Request,ad_id: str=Form(...),version: int=Form(...),archive: int=Form(...)):
        uid=access(request,True)
        try:
            with kufar.connect(root) as conn:
                result=kufarstock.archive_card(conn,ad_id,version,bool(archive),uid)
                published=False
                if result['changed']:
                    state=kufar.snapshot(conn)
                    kufar.publish(conn,state['revision'],uid)
                    published=True
            if archive and published:
                message='Карточка в архиве; файл на FTP обновлён одним файлом. После обработки Kufar объявление удалится.'
            elif archive:
                message='Карточка перемещена в архив локально. Она исчезнет из файла при следующей передаче полного файла.'
            elif published:
                message='Карточка возвращена из архива; файл на FTP обновлён. Kufar восстановит объявление после обработки файла.'
            else:
                message='Карточка возвращена из архива локально. Запись файла не найдена — карточка войдёт в файл при следующей сборке полного файла.'
            values=dict(section='inventory',ad=ad_id,message=message)
        except kufar.Error as exc:
            values=dict(section='inventory',ad=ad_id,error=str(exc))
        except sqlite3.OperationalError:
            values=dict(section='inventory',ad=ad_id,error='Раздел занят другой операцией. Повторите после её завершения.')
        except Exception:
            log.warning('Kufar archive card failed (%s)',__import__('sys').exc_info()[0].__name__)
            values=dict(section='inventory',ad=ad_id,error='Операция не подтверждена: файл на сервере не изменён, статус карточки откачен. Проверьте подключение к хостингу и повторите.')
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post('/kufar/full-candidate')
    def full_candidate(request: Request):
        uid=access(request,True)
        try:
            with kufar.connect(root) as local:
                current=root/'candidate'/'report.json'
                if current.exists() and json.loads(current.read_text(encoding='utf-8')).get('published'):
                    raise kufar.Error('Полный файл уже активирован. Для дальнейшей работы используйте обновление цен и остатков.')
                _,rows=kufarstock.load(local)
            product_ids=[row['product_id'] for row in rows if row['product_id']]
            with db(uid) as conn:
                products={row['product_id']:dict(row) for row in conn.execute("SELECT product_id,is_active,site_price FROM app.discount_product WHERE product_id=ANY(%s)",(product_ids,)).fetchall()}
            with kufar.connect(root) as local:
                report=kufarstock.build_full_candidate(local,products,root/'prepared/2026-11-04',root/'candidate',uid)
            message=(f"Полный файл собран локально: {report['records']} позиций. "
                     f"Актуальная цена подтверждена для {report['authoritative_prices']}; "
                     f"проверить вручную {report['prices_for_review']}. На FTP файл не отправлялся.")
            return redirect(message)
        except kufar.Error as exc:
            return redirect(str(exc),True)
        except Exception:
            log.warning('Kufar full candidate failed (%s)',__import__('sys').exc_info()[0].__name__)
            return redirect('Полный файл не собран. Предыдущий проверенный кандидат, если он был, не изменён. Повторите после проверки доступа к Kufar.',True)

    @router.post('/kufar/full-publish')
    def full_publish(request: Request):
        """Build the complete catalogue and hand it to FTP in one action."""
        uid=access(request,True)
        try:
            with kufar.connect(root) as local:
                current=root/'candidate'/'report.json'
                if current.exists() and json.loads(current.read_text(encoding='utf-8')).get('published'):
                    raise kufar.Error('Полный файл уже передан. Дальше поддерживайте его кнопкой «Актуализировать цены и остатки».')
                _,rows=kufarstock.load(local)
            product_ids=[row['product_id'] for row in rows if row['product_id']]
            with db(uid) as conn:
                products={row['product_id']:dict(row) for row in conn.execute("SELECT product_id,is_active,site_price FROM app.discount_product WHERE product_id=ANY(%s)",(product_ids,)).fetchall()}
            with kufar.connect(root) as local:
                kufarstock.build_full_candidate(local,products,root/'prepared/2026-11-04',root/'candidate',uid)
                revision=kufar.snapshot(local)['revision']
                count=kufar.activate_full_candidate(local,root/'candidate',revision,uid)
            message=(f'Готово: полный файл из {count} объявлений собран, проверен и передан на FTP. '
                     'Эту ссылку можно передавать Kufar для подключения импорта.')
            return redirect(message)
        except kufar.Error as exc:
            return redirect(str(exc),True)
        except Exception:
            log.warning('Kufar full publish failed (%s)',__import__('sys').exc_info()[0].__name__)
            return redirect('Полный файл не передан: прежний файл на сервере не изменён. Проверьте доступ к Kufar и хостингу, затем повторите.',True)

    @router.post('/kufar/activate-full-candidate')
    def activate_full_candidate(request: Request,revision: int=Form(...)):
        def run(conn,uid):
            count=kufar.activate_full_candidate(conn,root/'candidate',revision,uid)
            return f'Полный файл из {count} объявлений загружен на сервер и проверен. Эту ссылку можно передавать Kufar.'
        return perform(request,run)

    @router.post('/kufar/refresh-catalog')
    def refresh_catalog(request: Request,revision: int=Form(...)):
        uid=access(request,True)
        try:
            with kufar.connect(root) as local:
                state=kufar.snapshot(local);product_ids=[row['product_id'] for row in state['rows'] if row['product_id']]
            with db(uid) as conn:
                products={row['product_id']:dict(row) for row in conn.execute(
                    'SELECT product_id,is_active,site_price FROM app.discount_product WHERE product_id=ANY(%s)',(product_ids,)).fetchall()}
            with kufar.connect(root) as local:
                result=kufar.refresh_prices_and_stock(local,revision,products,uid)
            if result['published']:
                message=(f"Файл на сервере обновлён одним файлом: изменено цен {result['updated']}, "
                         f"снято и перемещено в архив {result['removed']} (новых записей архива: {result['archived']}). "
                         f"Без привязки осталось {result['unbound']}.")
            else:
                message=f"Цены и остатки уже актуальны. Без привязки осталось {result['unbound']} объявлений."
            return redirect(message)
        except kufar.Error as exc:
            return redirect(str(exc),True)
        except Exception:
            log.warning('Kufar catalog refresh failed (%s)',__import__('sys').exc_info()[0].__name__)
            return redirect('Обновление не подтверждено. Файл на сервере не заменён; повторите после проверки подключения.',True)

    @router.get('/kufar/full-candidate.xml')
    def full_candidate_download(request: Request):
        access(request)
        path=root/'candidate'/'kufar-full-candidate.xml'
        if not path.exists():
            raise HTTPException(404,'Сначала соберите полный файл-кандидат')
        return Response(path.read_bytes(),media_type='application/xml',headers={'Content-Disposition':'attachment; filename="kufar-full-candidate.xml"'})

    @router.post('/kufar/inventory/compare')
    def inventory_compare(request: Request):
        uid=access(request,True)
        source,rows,latest,*_=inventory_data(uid)
        if not latest:
            return RedirectResponse('/kufar?'+urlencode({'error':'Срез уценки ещё не загружен. Сначала обновите базу уценки.'}),303)
        with kufar.connect(root) as conn:
            conn.execute('UPDATE kufar_inventory SET compared_at=?',(kufar.now(),))
            detail=f"Сверено {len(rows)} объявлений: есть {sum(r['stock']=='present' for r in rows)}, отсутствуют в срезе {sum(r['stock']=='missing' for r in rows)}, требуют сопоставления {sum(r['stock'] in {'unknown','no_code'} for r in rows)}. Снятие автоматически не выполнялось."
            kufar.audit(conn,uid,'inventory-stock',detail)
        return RedirectResponse('/kufar?'+urlencode({'message':detail}),303)

    @router.post('/kufar/inventory/profile-scan')
    def inventory_profile_scan(request: Request,profile_url: str=Form(kufarstock.DEFAULT_PROFILE_URL)):
        uid=access(request)
        try:
            normalized,rows=kufarstock.scan_profile(profile_url)
            with kufar.connect(root) as conn:
                source,base=kufarstock.load(conn)
                live=dict(profile_url=normalized,rows=rows)
                new_ads,removed_ads=kufarstock.compare_live(base,live)
                kufarstock.store_live_scan(conn,normalized,rows,uid)
            detail=(f'Сайт Kufar прочитан: {len(rows)} объявлений. Предложено добавить {len(new_ads)}, '
                    f'предложено отметить снятыми {len(removed_ads)}. База объявлений и XML не изменены.')
            values={'section':'overview','proposal':'new','message':detail}
        except kufar.Error as exc:
            values={'section':'overview','error':str(exc)}
        except Exception:
            log.warning('Kufar profile scan failed (%s)',__import__('sys').exc_info()[0].__name__)
            values={'section':'overview','error':'Не удалось прочитать весь профиль Kufar. Предыдущая сверка сохранена; данные объявлений не изменены.'}
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post('/kufar/inventory/confirm-removed')
    def inventory_confirm_removed(request: Request,ad_id: str=Form(''),confirm_all: str=Form('')):
        uid=access(request,True)
        try:
            with kufar.connect(root) as conn:
                live=kufarstock.load_live_scan(conn)
                _,base=kufarstock.load(conn)
                _,proposals=kufarstock.compare_live(base,live)
                targets=[row['ad_id'] for row in proposals] if confirm_all else [ad_id]
                count=kufarstock.confirm_removed(conn,targets,uid)
            message=f'Подтверждено снятие {count} объявлений. Они сохранены в истории и больше не входят в рекомендации.'
            values={'section':'overview','proposal':'removed','message':message}
        except kufar.Error as exc:
            values={'section':'overview','proposal':'removed','error':str(exc)}
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post('/kufar/inventory/accept-new')
    def inventory_accept_new(request: Request,ad_id: str=Form(''),accept_all: str=Form('')):
        uid=access(request,True)
        try:
            with kufar.connect(root) as conn:
                count=kufarstock.accept_new_ads(conn,[] if accept_all else [ad_id],uid)
            message=(f'Добавлено в каталог: {count}. База объявлений пополнена; XML и размещение на Kufar не изменены. '
                     'Для цены и остатка привяжите карточку к позиции уценки.')
            values={'section':'overview','proposal':'new','message':message}
        except kufar.Error as exc:
            values={'section':'overview','proposal':'new','error':str(exc)}
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post('/kufar/inventory/check')
    def inventory_check(request: Request,ad_id: str=Form(...)):
        uid=access(request,True)
        with kufar.connect(root) as conn:
            kufarstock.schema(conn)
            if not conn.execute('SELECT 1 FROM kufar_inventory WHERE ad_id=?',(ad_id,)).fetchone():
                raise HTTPException(404,'Объявление не найдено')
        try:
            status,payload=kufarstock.check_public(ad_id)
            with kufar.connect(root) as conn:kufarstock.store_check(conn,ad_id,status,payload,uid)
            values=dict(section='inventory',ad=ad_id,message='Страница доступна на Kufar; описание и фото обновлены.' if status=='available' else 'Страница недоступна публично. Проверьте объявление в аккаунте Kufar.')
        except kufar.Error as exc:values=dict(section='inventory',ad=ad_id,error=str(exc))
        except Exception:values=dict(section='inventory',ad=ad_id,error='Проверка не удалась. Состояние публикации не изменено; повторите позже.')
        return RedirectResponse('/kufar?'+urlencode(values),303)

    @router.post("/kufar/settings")
    def settings(request: Request, protocol: str = Form("ftps"), host: str = Form(""), tls_name: str = Form(""), port: str = Form("21"), username: str = Form(""), password: str = Form(""), feed_path: str = Form(""), feed_url: str = Form(""), photo_path: str = Form(""), photo_url: str = Form("")):
        values = {k: v.strip() for k, v in dict(protocol=protocol, host=host, tls_name=tls_name, port=port, username=username, feed_path=feed_path, feed_url=feed_url, photo_path=photo_path, photo_url=photo_url).items()}
        return perform(request, lambda c,u: kufar.save_config(c, values, password, u), settings=True)

    @router.post("/kufar/sync")
    def sync(request: Request):
        return perform(request, lambda c,u: kufar.reconcile(c, u))

    @router.post("/kufar/save")
    def save(request: Request, unid: str = Form(...), version: int = Form(...), revision: int = Form(...), subject: str = Form(""), body: str = Form(""), price: str = Form(""), photos: str = Form(""), product_id: str = Form(""), removed: str = Form("")):
        draft = dict(subject=subject.strip(), body=body.strip(), price=price.strip().replace(",", "."), photos=list(dict.fromkeys(x.strip() for x in photos.splitlines() if x.strip())))
        return perform(request, lambda c,u: kufar.save_listing(c, unid, version, revision, draft, bool(removed), product_id, u), unid=unid)

    @router.post("/kufar/removal")
    def removal(request: Request, unid: str = Form(...), version: int = Form(...), revision: int = Form(...), removed: int = Form(...)):
        return perform(request, lambda c,u: kufar.set_removed(c, unid, version, revision, bool(removed), u), unid=unid)

    @router.post("/kufar/publish")
    def publish(request: Request, revision: int = Form(...)):
        def run(c, u):
            kufar.publish(c, revision, u)
            return "Файл на хостинге обновлён и проверен. Ожидается обработка Kufar; публикация ещё не подтверждена."
        return perform(request, run)

    @router.get("/kufar/drafts")
    def drafts(request: Request):
        access(request, True)
        with kufar.connect(root) as conn:
            s = kufar.snapshot(conn)
        for row in s["rows"]:
            if row["source_xml"]:
                row["source_xml"] = row["source_xml"].decode("utf-8")
        data = {"saved_at": kufar.now(), "baseline_hash": s["hash"], "listings": s["rows"]}
        return Response(json.dumps(data, ensure_ascii=False, indent=2), media_type="application/json", headers={"Content-Disposition": 'attachment; filename="kufar-drafts.json"'})

    @router.post("/kufar/discard")
    def discard(request: Request, revision: int = Form(...)):
        def run(c, u):
            if kufar.snapshot(c)["revision"] != revision:
                raise kufar.Error("Данные изменились. Обновите страницу.")
            c.execute("DELETE FROM listing WHERE source_xml IS NOT NULL")
            c.execute("UPDATE listing SET draft=NULL,removed=0,version=version+1")
            c.execute("UPDATE state SET revision=revision+1 WHERE id=1")
            kufar.audit(c, u, "discard", "Локальные изменения отменены; сопоставления сохранены")
            return "Черновики отменены. Файл на сервере не изменён."
        return perform(request, run)

    @router.post("/kufar/photo")
    def photo(request: Request, revision: int = Form(...), file: UploadFile = File(...)):
        content = file.file.read(kufar.MAX_PHOTO + 1)
        def run(c, u):
            url = kufar.upload_photo(c, revision, content, u)
            return "Фото загружено. Добавьте ссылку в карточку: " + url
        return perform(request, run)

    @router.post("/kufar/manual-count")
    def manual_count(request: Request, count: int = Form(...), revision: int = Form(...)):
        def run(c,u):
            if not 0 <= count <= 300 or kufar.snapshot(c)["revision"] != revision:
                raise kufar.Error("Проверьте число объявлений и обновите страницу.")
            c.execute("UPDATE state SET manual_count=?,manual_checked_at=?,revision=revision+1 WHERE id=1", (count,kufar.now()))
            kufar.audit(c,u,"manual-count",f"Ручных объявлений: {count}")
        return perform(request,run)

    @router.post("/kufar/create")
    async def create(request: Request):
        access(request, True)
        form = await request.form()
        values = {k:str(v).strip() for k,v in form.items() if isinstance(v, str)}
        uploads = [item for item in form.getlist("photo_files")
                   if hasattr(item, "filename") and item.filename]
        upload_contents = []
        for upload in uploads:
            upload_contents.append(await upload.read(kufar.MAX_PHOTO + 1))
        direct_urls = [value.strip() for value in values.get("photo_urls", "").splitlines()
                       if value.strip()]
        try:
            plan = kufar.photo_plan(values.get("photo_order", ""), direct_urls,
                                    len(upload_contents))
        except kufar.Error as exc:
            return redirect(str(exc), True)
        product_id = values.get("product_id", "")
        uid = require_user(request)
        with db(uid) as conn:
            discount = conn.execute("SELECT product_id FROM app.discount_product WHERE product_id=%s AND is_active", (product_id,)).fetchone()
            defect = conn.execute("SELECT p.id FROM app.defect_product p JOIN app.defect_stock_line l ON l.product_id=p.id JOIN app.defect_stock_import i ON i.id=l.import_id AND i.is_current WHERE p.article=%s LIMIT 1", (product_id,)).fetchone()
        if not discount and not defect:
            return redirect("Номенклатура не найдена в текущем остатке брака или уценки. Проверьте полный код и свежесть среза.", True)
        try:
            revision = int(values.get("revision", ""))
        except ValueError:
            raise HTTPException(400,"Неверная версия данных")
        def run(local, actor):
            hosted = {}
            ordered = []
            for kind, value in plan:
                if kind == "url":
                    ordered.append(value)
                else:
                    if value not in hosted:
                        hosted[value] = kufar.upload_photo(
                            local, revision, upload_contents[value], actor)
                    ordered.append(hosted[value])
            values["photos"] = "\n".join(ordered)
            kufar.create_listing(local, revision, product_id, values, actor)
            return ("Локальный черновик создан. Первое фото назначено главным; "
                    "файл на сервере ещё не отправлен.")
        try:
            unid = kufar.import_unid(product_id)
        except kufar.Error as exc:
            return redirect(str(exc), True)
        return perform(request, run, unid=unid)

    app.include_router(router)
