# -*- coding: utf-8 -*-
"""
매일 자동 수집 드라이버 (작업 스케줄러가 하루 1회 실행)
=====================================================
1) collect_national : 전국 실거래가 잔여분 마무리
2) gongsi_national  : 전국 공동주택 공시가격 (한도까지)
각 단계는 재개 가능하므로 매일 돌리면 결국 완료된다.
로그: 결과/전국/daily.log (append)
"""
import sys
import time
import traceback
from pathlib import Path

LOG = Path(__file__).with_name("결과") / "전국" / "daily.log"
LOG.parent.mkdir(parents=True, exist_ok=True)


class Tee:
    def __init__(self, *s): self.s = s
    def write(self, m):
        for x in self.s:
            try: x.write(m)
            except Exception: pass
    def flush(self):
        for x in self.s:
            try: x.flush()
            except Exception: pass


def notify_user():
    """전국 수집·배포 완료 시 사용자에게 직접 알림: 바탕화면 파일 + 토스트."""
    msg = ("부동산 전국 공시가격 수집이 완료되어, 연구포털이 전국(아파트+연립) 전체판으로 "
           "자동 갱신되었습니다.\n\n포털: https://aiforalab.com/budongsan/\n완료시각: "
           + time.strftime("%Y-%m-%d %H:%M:%S"))
    # 1) 바탕화면 알림 파일
    try:
        desktop = Path.home() / "Desktop"
        if not desktop.exists():
            desktop = Path.home() / "OneDrive" / "Desktop"
        if desktop.exists():
            (desktop / "★부동산_전국수집_완료.txt").write_text(msg, encoding="utf-8")
    except Exception:
        pass
    # 2) Windows 토스트 (best-effort, BurntToast 있으면)
    try:
        import subprocess
        ps = ('try{Import-Module BurntToast -ErrorAction Stop;'
              'New-BurntToastNotification -Text "부동산 전국 수집 완료","포털이 전국판으로 갱신됨 · aiforalab.com/budongsan"}'
              'catch{Add-Type -AssemblyName System.Windows.Forms;'
              '$n=New-Object System.Windows.Forms.NotifyIcon;'
              '$n.Icon=[System.Drawing.SystemIcons]::Information;$n.Visible=$true;'
              '$n.ShowBalloonTip(10000,"부동산 전국 수집 완료","포털이 전국판으로 갱신됨",'
              '[System.Windows.Forms.ToolTipIcon]::Info);Start-Sleep 12}')
        subprocess.Popen(["powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command", ps])
    except Exception:
        pass
    print("🔔 사용자 알림 발송(바탕화면 파일 + 토스트)", flush=True)


def main():
    fh = open(LOG, "a", encoding="utf-8")
    sys.stdout = sys.stderr = Tee(fh)
    stamp = time.strftime("%Y-%m-%d %H:%M:%S")
    print(f"\n{'='*60}\n[{stamp}] 일일 수집 시작")
    for step, mod in [("실거래가", "collect_national"), ("매칭키갱신", "match_national"), ("공시가격", "gongsi_national")]:
        try:
            print(f"\n--- {step} 단계 ---", flush=True)
            m = __import__(mod)
            m.main()
        except Exception:
            print(f"[오류] {step} 단계 예외:\n{traceback.format_exc()}", flush=True)

    # 완료 감지 + 전국 포털 자동 업데이트(1회)
    try:
        import gongsi_national
        rem = gongsi_national.pending_count()
        print(f"\n전국 공시가격 잔여 (PNU,연도): {rem}", flush=True)
        marker = LOG.parent / "_COLLECTION_DONE"
        if rem == 0:
            marker.write_text(time.strftime("%Y-%m-%d %H:%M:%S"), encoding="utf-8")
            print("✅✅✅ 전국 공시가격 수집 완료 ✅✅✅", flush=True)
            import national_update
            if national_update.DONE_MARK.exists():
                print("전국 포털 이미 배포됨 — 재배포 생략", flush=True)
            else:
                print("--- 전국 포털 자동 업데이트 시작 ---", flush=True)
                ok = national_update.main(do_deploy=True)
                print("전국 포털 업데이트 " + ("성공" if ok else "보류(게이트/오류)"), flush=True)
                if ok:
                    notify_user()
        elif marker.exists():
            marker.unlink()
    except Exception:
        print(f"[완료감지/자동배포 오류]\n{traceback.format_exc()}", flush=True)

    print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 일일 수집 종료", flush=True)
    fh.close()


if __name__ == "__main__":
    main()
