#!/usr/bin/env python3
"""Correlate local CVE associations with KEV; compute only explicitly declared clocks.
No cloud calls, notifications, policy selection or remediation operations.
"""
import argparse
from datetime import date, datetime, timedelta, timezone
import hashlib
import json
from pathlib import Path
import re
import sys


def read(path):
    raw = Path(path).read_bytes()
    return json.loads(raw), hashlib.sha256(raw).hexdigest()


def cve(value):
    if not isinstance(value, str) or not re.fullmatch(r'CVE-\d{4}-\d{4,}', value):
        raise ValueError('Malformed CVE identity')
    return value


def timestamp(value):
    if not isinstance(value, str):
        raise ValueError('Clock trigger must be a timestamp')
    result = datetime.fromisoformat(value.replace('Z', '+00:00'))
    if result.tzinfo is None:
        raise ValueError('Clock trigger must include timezone')
    return result.astimezone(timezone.utc)


def intake(findings_path, feed_path, clocks_path=None):
    findings, finding_hash = read(findings_path)
    feed, feed_hash = read(feed_path)
    population = findings.get('findings')
    vulnerabilities = feed.get('vulnerabilities')
    if not findings.get('scope') or not isinstance(population, list) or not population:
        raise ValueError('Nonempty explicitly scoped finding associations required')
    if not isinstance(vulnerabilities, list) or not vulnerabilities or type(feed.get('count')) is not int or feed['count'] != len(vulnerabilities):
        raise ValueError('Nonempty complete KEV catalog and matching count required')
    catalog = {}
    for row in vulnerabilities:
        identifier = cve(row.get('cveID'))
        if identifier in catalog:
            raise ValueError('Duplicate catalog CVE')
        date.fromisoformat(row['dateAdded'])
        if row.get('dueDate'):
            date.fromisoformat(row['dueDate'])
        catalog[identifier] = row
    clocks, clock_hash = {}, None
    if clocks_path:
        document, clock_hash = read(clocks_path)
        if not isinstance(document.get('clocks'), list):
            raise ValueError('Explicit clock list required')
        for row in document['clocks']:
            key = row.get('findingId')
            if not isinstance(key, str) or not key or key in clocks:
                raise ValueError('Missing or duplicate clock association')
            if row.get('approved') is not True or not all(isinstance(row.get(k), str) and row[k].strip() for k in ('basis','scope','reviewedBy')):
                raise ValueError('Clock review metadata missing')
            hours = row.get('withinHours')
            if type(hours) not in (int,float) or not 0 < hours <= 8760:
                raise ValueError('Invalid declared time window')
            timestamp(row.get('triggerAt'))
            cve(row.get('cve'))
            clocks[key] = row
    output, seen = [], set()
    for row in population:
        key = row.get('id')
        if not isinstance(key, str) or not key or key in seen or not row.get('resourceRef') or not row.get('sourceId'):
            raise ValueError('Missing or duplicate finding-association identity')
        seen.add(key)
        identifier = cve(row.get('cve'))
        match, clock = catalog.get(identifier), clocks.get(key)
        if clock and (clock['cve'] != identifier or not match):
            raise ValueError('Clock does not match a KEV finding association')
        item = {'findingId': key, 'sourceId': row['sourceId'], 'resourceRef': row['resourceRef'],
                'cve': identifier, 'kev': match is not None,
                'status': 'review_required' if match else 'not_in_this_kev_snapshot',
                'dueAt': None}
        if match:
            item.update({'dateAdded': match['dateAdded'], 'catalogDueDate': match.get('dueDate'),
                         'requiredAction': match.get('requiredAction')})
        if clock:
            due = timestamp(clock['triggerAt']) + timedelta(hours=clock['withinHours'])
            item.update({'status': 'computed_from_declared_clock', 'dueAt': due.isoformat(),
                         'triggerAt': clock['triggerAt'], 'basis': clock['basis']})
        output.append(item)
    if set(clocks) - seen:
        raise ValueError('Clock references an unknown finding association')
    return {'scope': findings['scope'], 'findingSha256': finding_hash, 'kevSha256': feed_hash,
            'clocksSha256': clock_hash, 'records': output,
            'boundary': 'Declared clock calculation only; reviewer identity, applicability and policy correctness are not verified.'}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('findings')
    parser.add_argument('kev_catalog')
    parser.add_argument('--clocks')
    args = parser.parse_args()
    try:
        result = intake(args.findings, args.kev_catalog, args.clocks)
    except (ValueError, TypeError, KeyError, OSError, AttributeError, OverflowError):
        print(json.dumps({'error': 'Invalid local findings, KEV catalog or declared clock'}))
        sys.exit(2)
    print(json.dumps(result))
