import copy
import hashlib
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
EDITION = ROOT / 'data/website-cost-service-2026-09-18'
DATE = '2026-09-18'


def write(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')


def artifact(path, download=None):
    raw = path.read_bytes()
    result = dict(path=str(path.relative_to(ROOT)), sha256=hashlib.sha256(raw).hexdigest(), bytes=len(raw))
    if download:
        result['download'] = download
        target = ROOT / 'website/public' / download.lstrip('/')
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(raw)
    return result


def main():
    catalog = json.loads((ROOT / 'data/website-portfolio-2035-2026-09-18/catalog.json').read_text())
    prior = copy.deepcopy(catalog)
    evidence = json.loads((EDITION / 'evidence.json').read_text())
    known = {row['id'] for row in catalog['sources']}
    for row in evidence['findings']:
        assert set(row['sources']) <= known
        assert row['locator'] and row['limitation']
    files = [artifact(EDITION / 'evidence.json', '/downloads/cost-service/evidence.json')]
    files += [artifact(ROOT / path) for path in evidence['input_paths']]
    files += [artifact(Path(__file__).resolve(), '/downloads/cost-service/build_website_cost_service.py')]
    catalog['sources'].append(dict(
        id='cost-service-review', title='Generation and dependable supply: cost comparison guide',
        publisher='WattInfo', kind='project-analysis', url='/downloads/cost-service/evidence.json',
        publicationDate=DATE, edition='Qualitative infographic and evidence map, 18 September 2026',
        retrievedAt=DATE, reviewedAt=DATE,
        locator='findings: generation, shared-services, equal-test, extension and recommendation; diagram text',
        note='Editorial synthesis of catalogued evidence. Diagram sizes are qualitative; no complete portfolio price or technology cost ranking is calculated. Existing extension results and new-build costs have separate boundaries.',
        artifacts=files,
    ))
    for key in ['sources', 'claims']:
        assert catalog[key][:len(prior[key])] == prior[key]
    for path in [EDITION / 'catalog.json', ROOT / 'website/src/data/catalog.json', ROOT / 'website/public/downloads/catalog.json']:
        write(path, catalog)
    print(f"{len(catalog['sources'])} sources; {len(catalog['claims'])} numerical claims; {len(evidence['findings'])} reviewed qualitative findings")


if __name__ == '__main__':
    main()
