#!/usr/bin/env python3
"""urlcheck.py - check the links in a draft before you publish.

Usage:
    python urlcheck.py DRAFT [SOURCE ...] [--online]

For every http(s) link found in DRAFT it reports:
  BAD FORMAT     the link is malformed (no host, spaces, unbalanced brackets)
  NOT IN SOURCE  SOURCE files were given and the link appears in none of them
  DEAD           with --online only: the server answered with an error or did not answer
Exit code 0 = all links fine, 1 = some problems, 2 = usage error.
Without --online it never touches the network. Only Python 3 standard library is used.

License: MIT
Copyright (c) 2026 Ye Xiaoguo AI Team
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software, to deal in the software without restriction, including the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies, subject to
including this notice. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
"""
import re
import sys
import urllib.error
import urllib.parse
import urllib.request

LINK = re.compile(r'https?://[^\s<>"\'）)\]，。、]+')
TRAIL = '.,;:!?'


def links(text):
    found = []
    for m in LINK.finditer(text):
        u = m.group().rstrip(TRAIL)
        if u not in found:
            found.append(u)
    return found


def well_formed(u):
    p = urllib.parse.urlsplit(u)
    host = p.hostname or ''
    return p.scheme in ('http', 'https') and '.' in host and not host.startswith('.') and not host.endswith('.')


def alive(u, timeout=10):
    req = urllib.request.Request(u, method='HEAD', headers={'User-Agent': 'urlcheck/1.0'})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status < 400
    except urllib.error.HTTPError as e:
        if e.code in (403, 405):  # some servers refuse HEAD; try GET
            try:
                with urllib.request.urlopen(urllib.request.Request(u, headers={'User-Agent': 'urlcheck/1.0'}), timeout=timeout) as r:
                    return r.status < 400
            except Exception:
                return False
        return False
    except Exception:
        return False


def read(path):
    with open(path, encoding='utf-8-sig') as f:
        return f.read()


def main(argv):
    online = '--online' in argv
    args = [a for a in argv[1:] if a != '--online']
    if not args:
        print(__doc__.strip().split('\n\n')[1])
        return 2
    try:
        draft = read(args[0])
        source = '\n'.join(read(p) for p in args[1:])
    except OSError as exc:
        print('cannot read file:', exc)
        return 2
    have = set(links(source)) if args[1:] else None
    problems = 0
    found = links(draft)
    for u in found:
        if not well_formed(u):
            print('BAD FORMAT:', u); problems += 1; continue
        if have is not None and u not in have:
            print('NOT IN SOURCE:', u); problems += 1
        if online and not alive(u):
            print('DEAD:', u); problems += 1
    print('checked %d links, %d problems' % (len(found), problems))
    return 1 if problems else 0


if __name__ == '__main__':
    sys.exit(main(sys.argv))
