import json, os, re, sys
from asc import rufe

A = '6831176682'
INFO = 'cb89f7c5-0dfe-4308-a9d7-12c1aa840427'
INFO_LOC = '3b372a04-d411-46de-9188-a32567b78847'
VERSION = 'd683962c-e2df-4858-bbab-99442534c409'
VER_LOC = '13ad3d75-78d2-46ef-8936-f68b4d5f9a0e'
BUILD6 = 'e5972f46-9f06-4b49-b7f2-7af3f889429e'
MD = open(os.path.expanduser('~/workspace/git.mqtec.de/software/amj-namaztimes-ds/app/store/APP-STORE.md')).read()

def melde(name, s, j):
    ok = 200 <= s < 300
    fehler = '' if ok else ' ' + json.dumps([(e.get('code'), e.get('detail')) for e in (j or {}).get('errors', [])] if isinstance(j, dict) else j, ensure_ascii=False)[:400]
    print(('OK   ' if ok else 'FAIL ') + name + f' ({s})' + fehler)
    return ok

def abschnitt(titel):
    m = re.search(r'\*\*' + re.escape(titel) + r'\*\*[^\n]*\n(.*?)(?=\n\*\*|\n## )', MD, re.S)
    return m.group(1).strip() if m else ''

beschreibung = abschnitt('Beschreibung:')
werbetext = 'Gebetszeiten, Ankündigungen und Bilder der Moschee-Anzeige direkt vom Telefon pflegen. Mit freiem Designer und Flyern für die WhatsApp-Gruppe.'
stichwoerter = 'Gebetszeiten,Moschee,Namaz,Salah,Jumma,Anzeige,Bildschirm,Flyer,Jamaat,Hadith,Gemeinde'
notiz = abschnitt('Notes:')
assert beschreibung.startswith('Mit Gebetszeiten Verwaltung') and notiz.startswith('This app'), (beschreibung[:40], notiz[:40])
pw = re.search(r'^Admin:\s*(\S+)', open(os.path.expanduser('~/.config/mqtec/gebetszeiten-test-zugaenge.txt')).read(), re.M).group(1)

# 1 App: Rechte an Inhalten
melde('Inhaltsrechte', *rufe('PATCH', f'/v1/apps/{A}', {'data': {'type': 'apps', 'id': A, 'attributes': {'contentRightsDeclaration': 'DOES_NOT_USE_THIRD_PARTY_CONTENT'}}}))

# 2 Kategorien
melde('Kategorien', *rufe('PATCH', f'/v1/appInfos/{INFO}', {'data': {'type': 'appInfos', 'id': INFO, 'relationships': {
    'primaryCategory': {'data': {'type': 'appCategories', 'id': 'UTILITIES'}},
    'secondaryCategory': {'data': {'type': 'appCategories', 'id': 'PRODUCTIVITY'}}}}}))

# 3 Name, Untertitel, Datenschutz
melde('Name, Untertitel, Datenschutz-URL', *rufe('PATCH', f'/v1/appInfoLocalizations/{INFO_LOC}', {'data': {'type': 'appInfoLocalizations', 'id': INFO_LOC, 'attributes': {
    'name': 'Gebetszeiten Verwaltung', 'subtitle': 'Die Moschee-Anzeige pflegen',
    'privacyPolicyUrl': 'https://gebetszeiten.hostdock.de/datenschutz.html'}}}))

# 4 Alterseinstufung: alles nein
enum_felder = ['alcoholTobaccoOrDrugUseOrReferences', 'contests', 'gamblingSimulated', 'gunsOrOtherWeapons', 'horrorOrFearThemes',
               'matureOrSuggestiveThemes', 'medicalOrTreatmentInformation', 'profanityOrCrudeHumor', 'sexualContentGraphicAndNudity',
               'sexualContentOrNudity', 'violenceCartoonOrFantasy', 'violenceRealistic', 'violenceRealisticProlongedGraphicOrSadistic']
bool_felder = ['advertising', 'gambling', 'healthOrWellnessTopics', 'lootBox', 'messagingAndChat', 'parentalControls', 'ageAssurance',
               'socialMedia', 'unrestrictedWebAccess', 'userGeneratedContent']
attr = {f: 'NONE' for f in enum_felder} | {f: False for f in bool_felder}
melde('Alterseinstufung', *rufe('PATCH', f'/v1/ageRatingDeclarations/{INFO}', {'data': {'type': 'ageRatingDeclarations', 'id': INFO, 'attributes': attr}}))

# 5 Version: Copyright, manuell veroeffentlichen, Build 6
melde('Version: Copyright, manuell', *rufe('PATCH', f'/v1/appStoreVersions/{VERSION}', {'data': {'type': 'appStoreVersions', 'id': VERSION, 'attributes': {
    'copyright': '2026 MQTec GmbH', 'releaseType': 'MANUAL'}}}))
melde('Version: Build 6', *rufe('PATCH', f'/v1/appStoreVersions/{VERSION}/relationships/build', {'data': {'type': 'builds', 'id': BUILD6}}))

# 6 Texte der Version
melde('Beschreibung, Stichwoerter, Werbetext, Support', *rufe('PATCH', f'/v1/appStoreVersionLocalizations/{VER_LOC}', {'data': {'type': 'appStoreVersionLocalizations', 'id': VER_LOC, 'attributes': {
    'description': beschreibung, 'keywords': stichwoerter, 'promotionalText': werbetext,
    'supportUrl': 'https://gebetszeiten.hostdock.de/'}}}))

# 7 Pruefhinweise
s, j = rufe('GET', f'/v1/appStoreVersions/{VERSION}/appStoreReviewDetail')
pruef = {'contactFirstName': 'Moneeb', 'contactLastName': 'Qureshi', 'contactPhone': '+49 6151 4935351',
         'contactEmail': 'moneeb.qureshi@mqtec.de', 'demoAccountName': 'admin', 'demoAccountPassword': pw,
         'demoAccountRequired': True, 'notes': notiz}
if s == 200 and j and j.get('data'):
    rid = j['data']['id']
    melde('Pruefhinweise (geaendert)', *rufe('PATCH', f'/v1/appStoreReviewDetails/{rid}', {'data': {'type': 'appStoreReviewDetails', 'id': rid, 'attributes': pruef}}))
else:
    melde('Pruefhinweise (angelegt)', *rufe('POST', '/v1/appStoreReviewDetails', {'data': {'type': 'appStoreReviewDetails', 'attributes': pruef,
        'relationships': {'appStoreVersion': {'data': {'type': 'appStoreVersions', 'id': VERSION}}}}}))

# 8 Preis: kostenlos, Basis Deutschland
s, j = rufe('GET', f'/v1/apps/{A}/appPricePoints?filter[territory]=DEU&limit=200')
frei = next((p['id'] for p in j.get('data', []) if p['attributes'].get('customerPrice') in ('0', '0.0', '0.00')), None)
if frei:
    melde('Preis kostenlos', *rufe('POST', '/v1/appPriceSchedules', {
        'data': {'type': 'appPriceSchedules', 'relationships': {
            'app': {'data': {'type': 'apps', 'id': A}},
            'baseTerritory': {'data': {'type': 'territories', 'id': 'DEU'}},
            'manualPrices': {'data': [{'type': 'appPrices', 'id': '${preis}'}]}}},
        'included': [{'type': 'appPrices', 'id': '${preis}', 'attributes': {'startDate': None},
                      'relationships': {'appPricePoint': {'data': {'type': 'appPricePoints', 'id': frei}}}}]}))
else:
    print('FAIL Preis: kein Preispunkt 0 gefunden', s)

# 9 Verfuegbarkeit: alle Laender, auch kuenftige
s, j = rufe('GET', '/v1/territories?limit=200')
laender = [t['id'] for t in j.get('data', [])]
melde(f'Verfuegbarkeit ({len(laender)} Laender)', *rufe('POST', '/v2/appAvailabilities', {
    'data': {'type': 'appAvailabilities', 'attributes': {'availableInNewTerritories': True},
             'relationships': {'app': {'data': {'type': 'apps', 'id': A}},
                               'territoryAvailabilities': {'data': [{'type': 'territoryAvailabilities', 'id': '${' + l + '}'} for l in laender]}}},
    'included': [{'type': 'territoryAvailabilities', 'id': '${' + l + '}', 'attributes': {'available': True, 'releaseDate': None, 'preOrderEnabled': False},
                  'relationships': {'territory': {'data': {'type': 'territories', 'id': l}}}} for l in laender]}))
