#!/usr/bin/env python3
"""Batch import JSONL into ZC.db (zc_projects)"""
import sys, json, sqlite3, os

if len(sys.argv) < 2:
    print('Usage: import_zc_batch.py <jsonl_path>')
    sys.exit(1)

path = sys.argv[1]
if not os.path.exists(path):
    print(f'File not found: {path}')
    sys.exit(1)

db = sqlite3.connect('/root/ZC.db')
db.execute('PRAGMA journal_mode=WAL')
db.execute('PRAGMA synchronous=OFF')
db.execute('PRAGMA busy_timeout=5000')

count = 0
with open(path, 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        r = json.loads(line)

        project_id = r.get('project_id', '') or ''
        if not project_id:
            continue

        # dedup: skip if project_id already exists
        cur = db.execute('SELECT 1 FROM zc_projects WHERE project_id = ?', (project_id,))
        if cur.fetchone():
            continue

        raw_json = r.get('raw_json', '') or json.dumps(r, ensure_ascii=False)

        db.execute('''
            INSERT INTO zc_projects (
                project_id, project_name, version_type, publish_date, phase,
                construction_period, total_investment, project_type,
                owner_nature, industry, topic, scale, quantity_scale,
                industry_level, province, city, detail_address,
                building_area, land_area, floors, foreign_investment,
                decoration, steel_structure, exterior_wall, parking,
                elevator, air_conditioning, fresh_air, heating, prefab,
                passive_house, construction_content, equipment_list,
                procurement_equipment, process_flow, schedule_overview,
                phase_approval, phase_design, phase_procurement,
                phase_construction, phase_contractor, phase_status, raw_json
            ) VALUES (?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?)
        ''', (
            project_id, r.get('project_name',''), r.get('version_type',''),
            r.get('publish_date',''), r.get('phase',''),
            r.get('construction_period',''), r.get('total_investment',''),
            r.get('project_type',''),
            r.get('owner_nature',''), r.get('industry',''),
            r.get('topic',''), r.get('scale',''),
            r.get('quantity_scale',''),
            r.get('industry_level',''), r.get('province',''),
            r.get('city',''), r.get('detail_address',''),
            r.get('building_area',''), r.get('land_area',''),
            r.get('floors',''), r.get('foreign_investment',''),
            r.get('decoration',''), r.get('steel_structure',''),
            r.get('exterior_wall',''), r.get('parking',''),
            r.get('elevator',''), r.get('air_conditioning',''),
            r.get('fresh_air',''), r.get('heating',''),
            r.get('prefab',''), r.get('passive_house',''),
            r.get('construction_content',''), r.get('equipment_list',''),
            r.get('procurement_equipment',''), r.get('process_flow',''),
            r.get('schedule_overview',''),
            r.get('phase_approval',''), r.get('phase_design',''),
            r.get('phase_procurement',''),
            r.get('phase_construction',''), r.get('phase_contractor',''),
            r.get('phase_status',''), raw_json
        ))
        count += 1
        
        # Import contacts from raw_json
        if raw_json:
            try:
                rj_data = json.loads(raw_json) if isinstance(raw_json, str) else raw_json
                rj_contacts = rj_data.get('contacts', r.get('contacts', []))
                if isinstance(rj_contacts, list) and len(rj_contacts) > 0:
                    for ct in rj_contacts:
                        db.execute(
                            "INSERT INTO zc_contacts (project_id, company, contact_name, department, position, phone, remarks, address, role) VALUES (?,?,?,?,?,?,?,?,?)",
                            (project_id,
                             ct.get('company','') or '',
                             ct.get('contact_name','') or '',
                             ct.get('department','') or '',
                             ct.get('position','') or '',
                             ct.get('phone','') or '',
                             ct.get('remarks','') or '',
                             ct.get('address','') or '',
                             ct.get('role','') or '')
                        )
            except Exception:
                pass  # contacts import is best-effort

db.commit()
total = db.execute('SELECT count(*) FROM zc_projects').fetchone()[0]
db.close()

print(f'OK:{count}')
print(f'Total in DB: {total}')
