#!/usr/bin/env python3
"""Audit publicly accessible pages on one owned domain to prioritize SEO improvements.
Not a Google ranking or indexing checker.
Install: pip install requests beautifulsoup4
Run: python seo_dir_analyzer.py https://example.com brandname --max-pages 100
"""
import argparse, csv, re, time, xml.etree.ElementTree as ET
from collections import deque, defaultdict
from urllib.parse import urljoin, urlsplit, urlunsplit, unquote
from urllib.robotparser import RobotFileParser
import requests
from bs4 import BeautifulSoup

AGENT = 'OwnedSiteSEOAudit/1.0 (+respect-robots)'

def canonical_url(raw, origin):
    p = urlsplit(urljoin(origin, raw))
    root = urlsplit(origin)
    if p.scheme not in ('http', 'https') or p.hostname != root.hostname:
        return None
    path = re.sub('/+', '/', p.path or '/')
    return urlunsplit((root.scheme, root.netloc, path, '', ''))

def text_of(tag):
    return tag.get_text(' ', strip=True) if tag else ''

def sitemap_urls(session, url, origin, seen=None, limit=400):
    seen = seen or set()
    if url in seen or len(seen) > 20:
        return []
    seen.add(url)
    try:
        r = session.get(url, timeout=12, allow_redirects=False)
        if r.status_code != 200 or len(r.content) > 5_000_000:
            return []
        root = ET.fromstring(r.content)
        links = [el.text.strip() for el in root.iter() if el.tag.endswith('}loc') or el.tag == 'loc' if el.text]
        if root.tag.endswith('sitemapindex'):
            out = []
            for link in links[:15]:
                out += sitemap_urls(session, link, origin, seen, limit)
                if len(out) >= limit: break
            return out[:limit]
        return [x for x in (canonical_url(link, origin) for link in links) if x][:limit]
    except (requests.RequestException, ET.ParseError, ValueError):
        return []

def directory(path):
    parts = [p for p in path.split('/') if p]
    if not parts: return '/'
    if path.endswith('/'): return '/' + '/'.join(parts) + '/'
    return '/' + '/'.join(parts[:-1]) + '/' if len(parts) > 1 else '/'

def main():
    ap = argparse.ArgumentParser(description='Single-domain SEO directory audit (no ranking guarantees)')
    ap.add_argument('domain', help='Owned website, e.g. https://example.com')
    ap.add_argument('brand', help='Brand or topic keyword to assess')
    ap.add_argument('--max-pages', type=int, default=80)
    ap.add_argument('--output', default='dir_report.csv')
    args = ap.parse_args()
    src = urlsplit(args.domain if '://' in args.domain else 'https://' + args.domain)
    origin = f'{src.scheme}://{src.netloc}'
    brand_tokens = set(re.findall(r'\w+', args.brand.casefold()))
    session = requests.Session()
    session.headers.update({'User-Agent': AGENT})
    rp = RobotFileParser()
    try:
        rr = session.get(origin + '/robots.txt', timeout=10, allow_redirects=False)
        rp.parse(rr.text.splitlines() if rr.ok else [])
    except requests.RequestException:
        print('Warning: robots.txt could not be read; stopping to avoid unauthorized crawling.')
        return
    seeds = [origin + '/'] + sitemap_urls(session, origin + '/sitemap.xml', origin)
    seeds += sitemap_urls(session, origin + '/wp-sitemap.xml', origin)
    queue = deque(dict.fromkeys(seeds))
    visited, rows = set(), []
    incoming = defaultdict(int)
    while queue and len(visited) < args.max_pages:
        url = queue.popleft()
        if url in visited or not rp.can_fetch(AGENT, url): continue
        visited.add(url)
        try:
            r = session.get(url, timeout=12, allow_redirects=False)
            if r.status_code != 200 or 'text/html' not in r.headers.get('content-type', ''): continue
            if urlsplit(r.url).hostname != src.hostname: continue
            soup = BeautifulSoup(r.text[:2_000_000], 'html.parser')
            title, h1 = text_of(soup.title), text_of(soup.find('h1'))
            description = soup.find('meta', attrs={'name': re.compile('^description$', re.I)})
            desc = description.get('content', '') if description else ''
            robots_meta = soup.find('meta', attrs={'name': re.compile('^robots$', re.I)})
            noindex = bool(robots_meta and 'noindex' in robots_meta.get('content', '').lower())
            canon = soup.find('link', attrs={'rel': lambda value: value and 'canonical' in value})
            canonical = canon.get('href', '') if canon else ''
            body = text_of(soup.body)[:25000]
            terms = set(re.findall(r'\w+', (title + ' ' + h1 + ' ' + body).casefold()))
            overlap = len(terms & brand_tokens) / len(brand_tokens) if brand_tokens else 0
            path = unquote(urlsplit(url).path)
            rows.append(dict(url=url, dir=directory(path), title=title[:130], h1=h1[:130], meta_description=desc[:155], noindex=noindex, canonical=canonical, brand_relevance=round(overlap, 2), words=len(body.split())))
            for a in soup.find_all('a', href=True):
                link = canonical_url(a['href'], origin)
                if link:
                    incoming[link] += 1
                    if link not in visited and len(queue) < 700: queue.append(link)
        except requests.RequestException:
            pass
        time.sleep(0.15)
    for row in rows:
        row['internal_links'] = incoming[row['url']]
        score = 0
        score += 35 * row['brand_relevance']
        score += min(row['internal_links'], 10) * 2
        score += 15 if row['title'] else 0
        score += 10 if row['h1'] else 0
        score += 10 if row['words'] >= 250 else 0
        score += 10 if row['meta_description'] else 0
        score -= 60 if row['noindex'] else 0
        row['audit_score'] = round(max(0, min(100, score)))
        row['notes'] = ('NOINDEX; ' if row['noindex'] else '') + ('low topical match; ' if row['brand_relevance'] == 0 else '') + ('review canonical' if row['canonical'] and canonical_url(row['canonical'], origin) != row['url'] else '')
    # Aggregation shows areas with actual discovered pages, never claims to predict rankings.
    groups = defaultdict(list)
    for r in rows: groups[r['dir']].append(r)
    summary = sorted(((d, len(items), round(sum(x['audit_score'] for x in items)/len(items), 1), round(sum(x['brand_relevance'] for x in items)/len(items), 2)) for d,items in groups.items()), key=lambda x: (x[2], x[1]), reverse=True)
    with open(args.output, 'w', encoding='utf-8-sig', newline='') as f:
        w = csv.DictWriter(f, fieldnames=['url','dir','audit_score','brand_relevance','internal_links','noindex','words','title','h1','meta_description','canonical','notes'])
        w.writeheader(); w.writerows(rows)
    print(f'\nDomain: {origin} | Keyword: {args.brand} | HTML pages scanned: {len(rows)}')
    print('Directory                         Pages  Audit  Topic match')
    for d,n,s,t in summary[:20]: print(f'{d[:33]:34} {n:>4}  {s:>5}  {t:.0%}')
    print('\nDetailed report:', args.output)
    print('Scores are on-page audit heuristics, NOT a likelihood of ranking. Use verified Search Console data to assess impressions/positions.')

if __name__ == '__main__': main()
